C program diagnosis: modifying a const union and printing its members\n\n#include<stdio.h>\n#include<stdlib.h>\n#include<string.h>\n\nunion employee {\n char name[15];\n int age;\n float salary;\n};\nconst union employee e1;\n\nint main()\n{\n strcpy(e1.name, "K");\n printf("%s", e1.name);\n e1.age = 85;\n printf("%d", e1.age);\n printf("%f", e1.salary);\n return 0;\n}

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:

  • union employee e1 is qualified with const.
  • Operations attempt to write into e1.name and e1.age.
  • strcpy requires a writable destination.


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 to avoid implicit declaration (modern compilers).



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

More Questions from Constants

Discussion & Comments

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