samuelbrody1249
samuelbrody1249

Reputation: 4767

Write a float in c

I know this is an incredibly basic question but I wanted to check my understanding on something. I want to pass an integer to a function that accepts a float. It will automatically be converted by the function but I want to make it explicit. Are there any additional options to do this?

myfunc(2.0);
myfunc((float) 2);
myfunc(2f); <-- any way to do the last one, or is that compiler-specific, or not supported at all?

Upvotes: 0

Views: 78

Answers (2)

Eric Postpischil
Eric Postpischil

Reputation: 222933

C 2018 6.4.4.2 defines a decimal floating-point constant to have either decimal point (.) or an exponent part (e or E followed by a signed integer). It can have a suffix, such as f for float, but it still must have a decimal point or exponent. So you need one of those two things to make it a floating-point constant rather than an integer constant. You can have 1.2, 1., .2, or 1e3 but not 1.

Hexadecimal floating-point constants also need either a point or an exponent, but the exponent begins with p or P (and the hexadecimal constant begins with 0x or 0X1).

Footnote

1 There is a typo in the C 2018 standard; it shows the hexadecimal prefixes as one of 0X or 0X. This was 0x or 0X in the 2011 standard, which is undoubtedly the intent.

Upvotes: 0

user5550963
user5550963

Reputation:

You have to have floating point number in front of the f, otherwise compiler will read numerical value as integer and complain.

myfunc(2.0f);

The above would work.

For whole numbers you have something like:

myfunc(2l);
myfunc(2u);

Thanks to @user3386109 so floating point suffixes are definitely in in standard 6.4.4.2p4

Upvotes: 1

Related Questions