In C programming, can we create a union whose members are pointers (for example, to allow the same storage to hold either an int* or a char*)? Choose the most accurate statement.

Difficulty: Easy

Correct Answer: Yes

Explanation:


Introduction / Context:
This question tests your understanding of what kinds of members a C union may contain. Many learners confuse unions with structs and sometimes believe pointer types are not allowed in unions. In reality, unions can contain almost any data member type permitted in C, including pointers, provided the members obey type and aliasing rules when accessed.


Given Data / Assumptions:

  • The topic is standard C (not C++), using ordinary hosted implementations.
  • We are asking about a union whose members are pointer types (for example int* and char*).
  • No compiler extensions are assumed or required.


Concept / Approach:
A union allocates a single block of storage large enough to hold its largest member. Any member may be read/written, but only the currently active one (the last written) has a defined value. The C standard places no restriction forbidding pointer members in a union. Therefore, defining union U { int *pi; char *pc; void *pv; }; is perfectly valid and common in systems code (for example, tagged variants or lightweight sum types).


Step-by-Step Solution:

Define a union with pointer members (e.g., int*, char*, void*). The union's size equals the maximum of the member pointer sizes (typically all equal). Assign to one member; reading the same bytes through another pointer member without an appropriate rationale is usually unspecified, but the act of defining the union is valid.


Verification / Alternative check:
You can compile a small program declaring such a union and print sizeof the union and its members; mainstream compilers (GCC/Clang/MSVC/Turbo C) accept it.


Why Other Options Are Wrong:

  • No: Incorrect; unions can have pointer members.
  • Only in C++: Incorrect; C also supports this.
  • Only if void*: Unnecessary; any pointer type is allowed.
  • Compiler-specific: Not required; it is standard C.


Common Pitfalls:
Confusing “definition is allowed” with “reading through a different member is defined.” Storing via one member and reading via an incompatible one is generally unspecified; however, the union declaration itself is valid.


Final Answer:
Yes

More Questions from Structures, Unions, Enums

Discussion & Comments

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