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

Discussion

What will be the output of the program?

#include <stdio.h>
#include <stdlib.h>

int main()
{
    union test
    {
        int i;
        float f;
        char c;
    };
    union test *t;
    t = (union test *)malloc(sizeof(union test));
    t->f = 10.10f;
    printf("%f", t->f);
    return 0;
}

 

  • A.10
  • B.Garbage value
  • C.10.100000
  • D.Error

Answer: C

Correct answer: 10.100000

The value is written to the union's float member and read back through the same member, so nothing is reinterpreted and the value is intact.

It prints as 10.100000 because %f defaults to six decimal places. Remember that a union holds only one member at a time, all sharing the same storage: writing t->f destroys whatever t->i or t->c contained, and reading a different member afterwards would reinterpret the float's bits.

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

Post your comment

Please log in or register to post a comment.