You pass an int
value ('a') for a %f
format expecting a float
or a double
. This is undefined behavior, which can result in different output for every execution of the same program. The second printf
has the same problem: %f
expects a float
or double
but you pass an int
value.
Here is a corrected version:
#include <stdio.h>
int main(void) {
int a = 50000;
float b = 'a';
printf("a = %d\n", a);
printf("b = %f\n", b);
printf("'a' = %d\n", 'a');
return 0;
}
Output:
a = 50000
b = 97.000000
'a' = 97
Compiling with more warnings enabled, with command line arguments -Wall -W -Wextra
lets the compiler perform more consistency checks and complain about potential programming errors. It would have detected the errors in the posted code.
Indeed clang
still complains about the above correction:
clang -O2 -std=c11 -Weverything fmt.c -o fmt
fmt.c:8:24: warning: implicit conversion increases floating-point precision: 'float' to 'double' [-Wdouble-promotion]
printf("b = %f\n", b);
~~~~~~ ^
1 warning generated.
b
is promoted to double
when passed to printf()
. The double
type has more precision than the float
type, which might output misleading values if more decimals are requested than the original type afforded.
It is advisable to always use double
for floating point calculations and reserve the float
type for very specific cases where it is better suited, such as computer graphics APIs, some binary interchange formats...