Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does printf and co differentiate between float and double

Since it isn't strongly typed I thought it just picked the right memory size and interpreted it based on the type of argument. But float and double both use %f and they are different sizes.

P.S. I can see how promotion via copying the value to a temp and casting(is this right?) might work but how does it work for scanfs/sscanf?

like image 277
Roman A. Taycher Avatar asked Jun 18 '11 11:06

Roman A. Taycher


People also ask

How do I printf a double?

A double in c can be printed by both using %f and %lf. Both the %f format specifier and the %lf format specifier represent float and double. The printf() in c treats both float and double the same.

When to use double vs float?

float is mostly used in graphic libraries for high processing power due to its small range. double is mostly used for calculations in programming to eliminate errors when decimal values are being rounded off. Although float can still be used, it should only be in cases when we're dealing with small decimal values.

Is 1.5 float or double?

And the reason the comparison succeeds with 1.5 is that 1.5 can be represented exactly as a float and as a double ; it has a bunch of zeros in its low bits, so when the promotion adds zeros the result is the same as the double representation.


1 Answers

It doesn't differentiate. It's not possible to receive a float as a vararg: any float argument that you provide is first promoted to double.

6.5.2.2/6 defines "default argument promotions", and /7 states that default argument promotions are applied to "trailing arguments", that is varargs denoted by ....

how does it work for scanfs/sscanf?

The %f format for scanf requires a pointer to float. %lf requires a pointer to double, %Lf requires a pointer to long double.

copying the value to a temp and casting(is this right?)

If you provide a float argument, then the implementation creates a temporary of type double, initializes it with the float value, and passes this as the vararg. Casting by definition is explicit conversion by use of the cast operator -- you can cast if you like in order to make it exactly clear to the reader what's going on, but float f = 3; printf("%f", f); is exactly the same as float f = 3; printf("%f", (double)f);. The default argument promotion has the same meaning as the cast.

like image 100
Steve Jessop Avatar answered Sep 21 '22 22:09

Steve Jessop