Hi, I'm trying to do something like the following: $ cat const.c union u { int a; const int b; }; int main(void) { union u u, v; u.a = 42; v = u; } $ cc -Wall -Wextra const.c const.c: In function ‘main’: const.c:12:11: error: assignment of read-only variable ‘v’ 12 | v = u; | ^ const.c:9:21: warning: variable ‘v’ set but not used [-Wunused-but-set-variable] 9 | union u u, v; | ^ The actual data I'm using is not just an int, but that serves to reproduce the problem easily. In reality, the union is more like this: struct rstr { const size_t length; const char *const start; }; union str { struct { size_t length; char *start; } w; struct rstr r; }; I don't see anywhere in C11 that makes this a constraint violation, and considering that the const member is fully overlapped by a non-const member, I don't see why this assignment would be bad. I couldn't find what's the exact semantics of assignment to a union, but I guess it's similar to initialization, and since the first member is non-const, this should be doable. Maybe it's a bit of unspecified behavior, precisely because nothing seems to specify it. Is that really a constraint violation, or should the compiler accept the code? Have a lovely day, Alex -- <https://www.alejandro-colomar.es/> Looking for a remote C programming job at the moment.
Attachment:
signature.asc
Description: PGP signature