C unions and initializers: identify the error in the following union initializations.\n\n#include <stdio.h>\n\nint main()\n{\n union a {\n int i;\n char ch[2];\n };\n union a z1 = { 512 };\n union a z2 = { 0, 2 };\n return 0;\n}\n

Difficulty: Medium

Correct Answer: Error: in initializing z2

Explanation:


Introduction / Context:
This question targets understanding of how unions are initialized in C and what is allowed in a brace-enclosed initializer for a union when no designated initializers are used.


Given Data / Assumptions:

  • union a has two members: int i and char ch[2].
  • z1 is initialized with a single value 512.
  • z2 is initialized with two values: 0 and 2.


Concept / Approach:
When initializing a union without designators, only the first member may be initialized. The initializer corresponds to that first member’s type. For union a, the first member is int i. Therefore a single value that can initialize i is valid. Supplying multiple values as if initializing an array or struct is invalid for a union without designators.


Step-by-Step Solution:

z1 = { 512 } initializes the first member i with 512 → valid.z2 = { 0, 2 } attempts to provide two initializers for a union → invalid in this form.Hence the error is in initializing z2, not in the union declaration.


Verification / Alternative check:
A correct way to initialize the char array member would be to make it the first member or to use a designated initializer if supported (e.g., .ch = { 0, 2 }).


Why Other Options Are Wrong:

  • Error: invalid union declaration: The union is declared correctly.
  • No error / None of the above: Not true because z2’s initializer is invalid as written.


Common Pitfalls:
Confusing struct and union initialization rules, and forgetting that only one member exists at a time in a union, with the initializer mapping to the first member unless designated otherwise.


Final Answer:
Error: in initializing z2

More Questions from Structures, Unions, Enums

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion