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

Discussion

What is the output of this 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

The address of an int is passed to a function expecting a float *, so the four bytes holding 10 are read as though they were an IEEE single-precision float.

The bit pattern 0x0000000A read that way is a subnormal number of about \( 1.4 \times 10^{-44} \), which %f prints as 0.000000. No conversion takes place - the same bits are simply reinterpreted. Note that the mismatched pointer types would draw a diagnostic in any modern compiler.

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

Post your comment

Please log in or register to post a comment.