Machine-translated by Google. Questions are authored in English.
Top

Discussion

What will be the output of the following C code?

#include <stdio.h>
    void foo(float *);
    int main()
    {
        int i = 10, *p = &i;
        foo(&i);
    }
    void foo(float *p)
    {
        printf("%f\n", *p);
    }

 

  • A.10.000000
  • B.0.000000
  • C.Compile time error
  • D.Undefined behaviour

Answer: B

Correct answer: 0.000000

foo expects a float * but is given an int *. The pointer types are incompatible, so a conforming compiler must diagnose this - but the code compiles with a warning on most implementations, and the resulting behaviour is what the question asks about.

Inside foo, the four bytes holding the integer 10 are reinterpreted as a float. The bit pattern 0x0000000A read as an IEEE single is a denormal of the order of \( 10^{-44} \), which prints as 0.000000 at the default precision. The value is an accident of representation, not a conversion.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.