-1

I'm using gcc to compile this:

int a=1;
printf("%d\n",a);
printf("%f\n",a);
printf("%f\n",(float)a);

I get:

1
0.000000
1.000000

Why does the implicit conversion give a wrong output?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
anon_16
  • 329
  • 2
  • 3
  • 11

7 Answers7

3

There is no conversion. printf is not a function that accepts a float. It is a function that accepts an argument list that could be of any type.

The compiler assumes that a float was given and you are seeing basically undefined behaviour.

There is no mechanism that will parse your input string and then apply custom conversion on each parameter. You should be very careful with what you pass to printf cause exploits can be opened this way.

odedsh
  • 2,594
  • 17
  • 17
2

Because a double (which %f expects) probably is larger than an int on your platform. There is no "implicit conversion"; it will pass an int as the second argument and printf() will read a double.

This is undefined behavior by the way, don't do it.

unwind
  • 391,730
  • 64
  • 469
  • 606
2

In your code

int a=1;
//something
printf("%f\n",a);

there is no implicit conversion, rather an inappropriate usage of format specifier, which produces undefined behaviour.

Related: C11 standard, chapter ยง7.21.6.1, fprintf() function

If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

Because using the wrong format specifier is undefined behavior. It could print anything.

In realty it depends on the ABI and how it passes float arguments versus int arguments. In many systems floating point values are passed in registers reserved for this use, while int values are passed in different registers. This seems to be the case here.

Nikolai Ruhe
  • 81,520
  • 17
  • 180
  • 200
0

There is no conversion in the 2nd printf. You are invoking Undefined Behaviour by mismatching the conversion specifier (the "%f") and the type of value (an int).

pmg
  • 106,608
  • 13
  • 126
  • 198
0

By doing printf("%f\n",a); you are invoking an undefined behaviour. Whereas, by doing printf("%f\n",(float)a); you type cast the integer a so it prints the value as float as expected.

WedaPashi
  • 3,561
  • 26
  • 42
0

printf obtains its parameters in their own binary format. The format string is actually a description how to interpret such binary data. If this format string doesn't correspond to the actually provided binary data the behaviour is undefined at best.

dlask
  • 8,776
  • 1
  • 26
  • 30