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

Discussion

What will be the output of the following code −

#include <stdio.h>
#include <stdlib.h>
int main() {
   union my_union {
      int i;
      float f;
      char c;
   };
   union my_union* u;
   u = (union my_union*)malloc(sizeof(union my_union));
   u->f = 20.60f;
   printf("%f", u->f);
   free(u);
   return 0;
}

  • A.Garbage Value
  • B.20.600000
  • C.Syntax Error
  • D.20.6

Answer: B

Correct answer: 20.600000

The value is stored in the union's float member and read back through the same member, so no type punning is involved and the value survives intact.

It prints as 20.600000 because %f defaults to six decimal places. The bare 20.6 is what the source contains but not what printf produces without a precision specifier. Note that a union holds only one member at a time - writing u->f overwrites whatever u->i or u->c held.

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

Post your comment

Please log in or register to post a comment.