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

Discussion

Pick the best statement for the below program:

#include "stdio.h"
 
int main()
{
 union {int i1; int i2;} myVar = {.i2 =100};
 printf("%d %d",myVar.i1, myVar.i2);
 return 0;
}

 

  • A.Compile error due to incorrect syntax of initialization.
  • B.No compile error and it’ll print “0 100”
  • C.No compile error and it’ll print “100 100”

Answer: C

Correct answer: No compile error and it’ll print “100 100”

The two members of a union share the same storage, so writing 100 through i2 makes it visible through i1 as well - and since both are int, the bytes are interpreted the same way. The output is 100 100. (Reading a union through a member other than the one last written is only well defined when the types match like this.)

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

Post your comment

Please log in or register to post a comment.