Introduction / Context:
Declaring an object as const in C makes the entire object read-only. For aggregates such as structs and unions, each member becomes non-modifiable through that object. Attempting to write into a member via functions like strcpy therefore violates const-correctness and must be diagnosed by the compiler. This question highlights how const applies transitively to members of a union and how that affects typical string-copy operations.
Given Data / Assumptions:
- union employee { char name[15]; int age; float salary; };
- const union employee e1; declares a read-only union object.
- strcpy(e1.name, "K"); attempts to modify a member array.
Concept / Approach:
- Because e1 is const, its member name is a non-modifiable lvalue. Passing it to strcpy (which expects a char * destination) is illegal: the expression has type const char * after array-to-pointer decay.
- Compilers typically emit diagnostics such as 'assignment of read-only location' or 'lvalue required' for the attempted write.
- Even if forced via casts, modifying a const object produces undefined behavior.
Step-by-Step Solution:
Check object qualification: e1 is const → all members non-modifiable.strcpy destination requires writable memory → e1.name is not writable.Compilation fails with an error indicating invalid attempt to write to a const object.
Verification / Alternative check:
If e1 were non-const, strcpy would compile; or, if you used a separate writable buffer, no error would occur.
Why Other Options Are Wrong:
- RValue required: the issue is not rvalue vs lvalue, but non-modifiable lvalue.
- Type-conversion message about int pointers: unrelated to this code.
- No error/Runtime crash only: incorrect; this is a compile-time const violation.
Common Pitfalls:
- Casting away const to appease strcpy; writing through such a cast is undefined behavior.
- Assuming const applies only to scalars; it applies to aggregates as well.
Final Answer:
Error: LValue required in strcpy
Discussion & Comments