-1

If I try to print a float as an int, this code:

main () {                         
    float a = 6.8f;                      
    printf("%d", a);                      
}                       

prints 1073741824, while this code:

main () {            
    float a = 9.5f;           
    printf("%d", a);            
}                   

prints 0.

Is the output undefined? Also when is %f used with integer and %d used with double?

Greg
  • 9,068
  • 6
  • 49
  • 91
akash
  • 1,801
  • 7
  • 24
  • 42
  • output is garbage or undefined operation? – akash May 24 '13 at 09:58
  • 2
    possible duplicate of [print the float value in integer in C language](http://stackoverflow.com/questions/1632080/print-the-float-value-in-integer-in-c-language) – Leo Chapiro May 24 '13 at 09:59
  • 1
    Also calling a function that accepts a variable number of arguments (`printf()`) without a prototype in scope is UB. Use `#include ` for the proper prototype. – pmg May 24 '13 at 10:06

4 Answers4

2

Not only the output, but the entire program has undefined behavior, since type of the value you are passing to printf() does not match the type the format string expects.

2

From the C99 standard section 7.19.6.1 The fprintf function:

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

%d expects an int, not a float, so the program has undefined behaviour (including the output).

hmjd
  • 120,187
  • 20
  • 207
  • 252
1

As described in previous answers if the print format doesn't match the type passed, it shows undefined behavior.

If you want to view integer as float u need to typecast it.

int j = 5;
printf("%f",(float)(j));

This will print output as 5.0 ie as a floating digit number

suraj
  • 283
  • 3
  • 5
  • 13
0

The C Standard says that the printf format must match the type passed in. If it doesn't, the behavior is expressly undefined:

C99, 7.19.6.1 # 9 (fprintf)

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

Jens
  • 69,818
  • 15
  • 125
  • 179