public inbox for gcc-help@gcc.gnu.org
 help / color / mirror / Atom feed
* Assignment of union containing const-qualifier member
@ 2024-01-30 21:45 Alejandro Colomar
  2024-01-31 18:14 ` Alejandro Colomar
  0 siblings, 1 reply; 12+ messages in thread
From: Alejandro Colomar @ 2024-01-30 21:45 UTC (permalink / raw)
  To: gcc-help

[-- Attachment #1: Type: text/plain, Size: 1564 bytes --]

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 #2: signature.asc --]
[-- Type: application/pgp-signature, Size: 833 bytes --]

^ permalink raw reply	[flat|nested] 12+ messages in thread

end of thread, other threads:[~2024-03-18  9:23 UTC | newest]

Thread overview: 12+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2024-01-30 21:45 Assignment of union containing const-qualifier member Alejandro Colomar
2024-01-31 18:14 ` Alejandro Colomar
2024-02-04  7:33   ` Amol Surati
2024-02-04  8:18     ` Amol Surati
2024-02-04 18:40     ` Alejandro Colomar
2024-02-04 20:37       ` Alejandro Colomar
2024-02-07  4:13       ` Amol Surati
2024-02-07 13:29         ` Alejandro Colomar
2024-02-12 10:45           ` Amol Surati
2024-02-12 11:18             ` Amol Surati
2024-03-18  9:19             ` Alejandro Colomar
2024-03-18  9:23               ` Alejandro Colomar

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).