Question

I just wrote something to test the sizeof operator.

Firstly, when I build this program, GCC give me a warning.

main(){
    printf("%d", (2*3.14f));
}
// test.c|2|warning: format '%d' expects argument of type 'int',
// but argument 2 has type 'double' [-Wformat=]

So GCC believes the type of (2*3.14f) is double.

Then I added a sizeof operator, I assume the output will be exactly 8, which is the size of double.

main(){
    printf("%d", sizeof(2*3.14f));
}
//Output: 4

This is really confusing. So the question is: what is the type of (2*3.14f)?

Was it helpful?

Solution

(2*3.14f) has type float. It is promoted to double when passed to a variadic function, hence the reference to double in the error message from GCC.

If you wish to display a float converted to int, use printf("%d", (int)…);

If you wish to display the bits of a float as if it were an int, use:

int i;
assert(sizeof(f) == sizeof(i));
memcpy(&i, &f, sizeof(f));
printf("%d", i);

OTHER TIPS

Both invocations have undefined behaviour. Indeed, the first argument has type double and the second size_t, so you must use format specifiers %f and %zu, respectively.

(The type of 2 * 3.14f is float, because of the usual arithmetic conversions, but the argument is promoted to double under the floating point conversions because you're passing it as a variable argument.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top