In C, can a structure contain a nested union as one of its members?

Difficulty: Easy

Correct Answer: Correct — a structure may include a union member

Explanation:


Introduction / Context:
C supports aggregate nesting: structs can contain other structs or unions, and vice versa. This is common in low-level data layouts and protocol headers.


Given Data / Assumptions:

  • Standard C features apply.
  • We are defining a struct with multiple members.


Concept / Approach:
A struct can include a union member directly. The union occupies space within the struct according to its own size and alignment, and the struct’s size reflects all members plus padding.


Step-by-Step Solution:
1) Define union U with several fields.2) Define struct S { int x; union U u; }.3) This compiles and is portable; the union is a regular member.4) Access union members via s.u.member (or s_ptr->u.member for pointers).


Verification / Alternative check:
Write a minimal example and inspect sizeof(S); it includes space for the union and necessary padding.


Why Other Options Are Wrong:
Option B: The standard permits this nesting.
Option C: Unions can have multiple members.
Option D: No special pragmas are required.
Option E: This is valid in both C and C++.


Common Pitfalls:
Misunderstanding the difference between struct (members laid out sequentially) and union (members overlapping) when nested.


Final Answer:
Correct — a structure may include a union member.

More Questions from Structures, Unions, Enums

Discussion & Comments

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