Path: csiph.com!eternal-september.org!reader02.eternal-september.org!.POSTED!not-for-mail
From: Tim Rentsch
Newsgroups: comp.std.c
Subject: Re: Assignment between union object members of incompatible types
Date: Tue, 01 Dec 2020 02:49:10 -0800
Organization: A noiseless patient Spider
Lines: 33
Message-ID: <86a6uxpzrt.fsf@linuxsc.com>
References: <272ec269-16e7-4e06-b8a8-e5f6534e66a8n@googlegroups.com>
Mime-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Injection-Info: reader02.eternal-september.org; posting-host="af7d4b2a5c3e9b4ea4551b168bc8c616"; logging-data="31358"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+aZXusuZ+K8VYgneIQXRFY106SA7tIj60="
User-Agent: Gnus/5.11 (Gnus v5.11) Emacs/22.4 (gnu/linux)
Cancel-Lock: sha1:Gw8VNNMgpcJlTSw/MHrH8PloK3A= sha1:/mSYvSJ+YxzXrXLePyXpyZxAQ54=
Xref: csiph.com comp.std.c:6163
Ian Abbott writes:
> A question (not posted by myself) from https://stackoverflow.com/questions/65077630 :
>
> Consider the following:
>
> union { int i; char c; } x = {0};
> x.c = x.i;
>
> Does the assignment x.c = x.i result in undefined behavior?
>
> C18 6.15.16.1/3 says:
As elsewhere noted, the reference is 6.5.16.1 paragraph 3.
> | If the value being stored in an object is read from another object
> | that overlaps in any way the storage of the first object, then the
> | overlap shall be exact and the two objects shall have qualified or
> | unqualified versions of a compatible type; otherwise, the behavior is
> | undefined.
>
> The objects x.c and x.i overlap, but have incompatible types, so on
> first glance it appears to be UB.
The value to be stored is read from object x.i. This value is
being stored in object x.c.
The object x.i overlaps with object x.c.
The overlap is not exact (probably). The two types involved are
not qualified or unqualified versions of a compatible type.
The assignment has undefined behavior. No doubt about it.