Accessing union members in C: Do we always need the address-of (&) operator, or do we use the member access operator (.) to read/write fields?

C Programming Structures, Unions, Enums Difficulty: Easy
Choose an option
  • A
    Use the member access operator (.) on the union object; & is only for obtaining an address.
  • B
    Always use & to access union elements.
  • C
    Use -> even when you have an object, not a pointer.
  • D
    Use sizeof to access members safely.
  • E
    Access requires a special pragma.

Answer

Correct Answer: Use the member access operator (.) on the union object; & is only for obtaining an address.

Explanation

Introduction / Context: C provides different operators for accessing data. This question focuses on how to access union members and clarifies the roles of the . (member access), -> (pointer dereference then member access), and & (address-of) operators.

Given Data / Assumptions:

  • A union variable exists, e.g., `union U u;`
  • We want to read or write its fields.

Concept / Approach: To access a member of a union object directly, use the `.` operator: `u.x = 5;`. If you have a pointer to a union, use `->`: `pu->x`. The `&` operator merely produces the address of the union object or a member; it does not read or write values.

Step-by-Step Solution: 1) With an object: `u.member` reads/writes the member. 2) With a pointer: `p->member` is equivalent to `(*p).member`. 3) Use `&u` or `&u.member` only when a function requires an address parameter. 4) Conclude that `&` is not for accessing members’ values.

Verification / Alternative check: Compile small examples to see that `u.member` works, while attempting to treat `&` as an access operator is a category error.

Why Other Options Are Wrong: Option B: Misuses `&`.
Option C: `->` requires a pointer; using it on a non-pointer is invalid.
Option D/E: Not meaningful for member access.

Common Pitfalls: Confusing `.` and `->`; taking addresses unnecessarily; aliasing concerns when switching active union members.

Final Answer: Use `.` (or `->` with a pointer). `&` only obtains an address.

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