0
int a=3.14*150;
printf("%d",a);
return 0;

This works fine, output is 471

int a=3.14*150;
printf("%f",a);
return 0;

but now the output is -0.104279 I thought int will be promoted to float but output is totally different I am using gcc 4.7.2 ubuntu 12.10

  • No, it won't be promoted. Try `float f=a; printf("%f",f);` – r3mainer Apr 25 '14 at 08:37
  • sizeof(int) is 4 Byte and sizeof(float) also 4 byte. But if you try to printf your int as float, the part of your bits stands on decimal places. I think you could shift your bytes left two times to see the right value as float. – Watsche Apr 25 '14 at 08:47

3 Answers3

2

It is undefined behaviour to use wrong conversion specifier for printf. (It's true of scanf as well).

Now, the %f conversion specifier means that the bits of the int variable a will be interpreted as a floating point value. Floating-point values are generally implemented as per IEEE Standard for Floating-Point Arithmetic (IEEE 754) though this is not mandated by the standard. This explains why your output is not what you expect.

ajay
  • 9,402
  • 8
  • 44
  • 71
1

printf doesn't inspect element types - it assumes you're being honest and that you're actually passing what you say you're going to pass. It's undefined behavior printing types with specifiers that don't match.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
0

The sizes differ, so this is undefined behavior. There can't be any promotion based on information in the format string, that's not how the language works. The printf() function is just a function.

unwind
  • 391,730
  • 64
  • 469
  • 606