The C99 standard talks about doubles in the specification for fprintf
(which subsequently applies to printf
). It says "a double
argument representing a floating-point number is converted..." Then in paragraph 9, it says:
If a conversion specification is invalid, the behavior is undefined. If any argument is not the correct type for the corresponding specification, the behavior is undefined.
So I would expect the following to be undefined behavior but my compiler doesn't warn about it.
double d = 2.0;
float f = 2.0f;
printf("%f", d);
printf("%f", f); // here
On the other hand, the specification for fscanf
says "floating point number" instead of double. Is it undefined behavior like this user claims?
Passing a float
to printf
is not undefined behavior--it's simply an impossibility. The float
will be promoted to double
before printf
receives it.
scanf
is different because what you're (at least normally) passing to scanf
are pointers rather than the data objects themselves. Since you're passing a pointer to the original data, with scanf
you need to distinguish between a float
and a double
.
float
in vararg functions are always promoted to double
.
scanf
deals with pointers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With