C program diagnosis: modifying a const union and printing its members
#include
#include
#include
union employee {
char name[15];
int age;
float salary;
};
const union employee e1;
int main()
{
strcpy(e1.name, "K");
printf("%s", e1.name);
e1.age = 85;
printf("%d", e1.age);
printf("%f", e1.salary);
return 0;
}
-
AError: RValue required
-
BError: cannot modify const object
-
CError: LValue required in strcpy
-
DNo error
-
EWarning only; program runs
Answer
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
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