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

Discussion

What is the output of this C code?

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

 

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

Answer: D

Correct answer: 0.000000

The cast is on the pointer this time, so the compiler accepts it and reads the four bytes holding the integer 10 as though they were an IEEE single-precision float.

The bit pattern 0x0000000A interpreted that way is a subnormal number of about \( 1.4 \times 10^{-44} \), which %f prints to six decimal places as 0.000000. Nothing is converted - the same bits are simply given a different meaning, which is what type punning through a pointer does.

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

Post your comment

Please log in or register to post a comment.