Difficulty: Medium
Correct Answer: Error: cannot modify const object
Explanation:
Introduction / Context:
This item tests const-correctness with aggregates. The union instance e1 is declared const, yet the code attempts to modify its members via strcpy and direct assignment.
Given Data / Assumptions:
Concept / Approach:
In C, const at the object level forbids any modification through that object. Accessing a member of a const union yields a const-qualified lvalue for that member. Therefore, both strcpy(e1.name, ...) and e1.age = 85 violate const-correctness.
Step-by-Step Solution:
Declaration: const union employee e1; → all member writes are forbidden.strcpy(e1.name, "K"); → attempts to write into a const char array → constraint violation.e1.age = 85; → attempts to write into const int → also a violation.Even reading different members of a union is fine, but writing is disallowed due to const.
Verification / Alternative check:
Remove const (union employee e1;) or use a non-const temporary. Also add #include
Why Other Options Are Wrong:
“RValue/LValue required” do not describe the fundamental issue. “No error” is false; compilers diagnose attempts to modify const objects.
Common Pitfalls:
Assuming const applies only to the union itself but not its members; forgetting to include string.h; misunderstanding that union type does not change const semantics.
Final Answer:
Error: cannot modify const object
Discussion & Comments