-5
# include <stdio.h>

int main()
{
 int a=4;
 printf("%f",a);
}

Output

0.000000 

Also

# include <stdio.h>

int main()
{
 float a=4.5;
 printf("%d",a);
}

Output

0

Can anyone explain the behaviour of the above outputs ? I know using different coversion specification is stupid, but i am just asking for the theoretical purpose.

Aman Singh
  • 743
  • 1
  • 10
  • 20
  • 2
    [**Unexpected output of printf()**](http://stackoverflow.com/questions/17898186/unexpected-output-of-printf/17898217#17898217) - `if type is not compatible with the type of the actual next argument (as promoted according to the default argument promotions), the` **`behavior is undefined`** – Grijesh Chauhan Jul 28 '13 at 12:02

2 Answers2

2

Can anyone explain the behaviour of the above outputs ?

It is undefined behavior.

(C11, 7.1.4p1) "If an argument to a function has [...] or a type (after promotion) not expected by a function with variable number of arguments, the behavior is undefined"

For the sake of history, there is a C Defect Report (DR#83) that addresses this exact same question:

http://www.open-std.org/jtc1/sc22/wg14/docs/rr/dr_083.html

ouah
  • 142,963
  • 15
  • 272
  • 331
  • You might want to clarify that that defect report is on the standard itself rather than the language. The standard didn't say (at that point) that it was undefined. – paxdiablo Jul 28 '13 at 12:07
0

printf is not type safe. It is your responsibility that the arguments are of the expected type, or else undefined behavior occurs.

Things are more interesting because the type of the arguments are default promoted: short/char -> int, float -> double.

Your examples are undefined behavior, so you can get anything, but what's probably happening under the hood is that the bytes that comprise the actual argument are interpreted as if they where of the type specified in the string format. Note that float is promoted to double and %f specificies also a double, which is likely 8 bytes, while int is probably 4 bytes...

rodrigo
  • 94,151
  • 12
  • 143
  • 190