Path: csiph.com!eternal-september.org!reader02.eternal-september.org!.POSTED!not-for-mail From: Keith Thompson Newsgroups: comp.std.c Subject: Re: Assignment between union object members of incompatible types Date: Mon, 30 Nov 2020 12:20:02 -0800 Organization: None to speak of Lines: 40 Message-ID: <87czzuoavh.fsf@nosuchdomain.example.com> References: <272ec269-16e7-4e06-b8a8-e5f6534e66a8n@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain Injection-Info: reader02.eternal-september.org; posting-host="2040853176253657d3e4e1ab772f5b0a"; logging-data="26045"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/rWsxq2ibyszcf71OcwdoZ" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/26.3 (gnu/linux) Cancel-Lock: sha1:8SoooC4ibkGX/TTWV1jBocLJYYk= sha1:2xfmWROHup3dosOGfNRoi1uJTq4= Xref: csiph.com comp.std.c:6162 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: > > | 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. On first glance, yes, but I think this passage needs to be updated to reflect its intent. The RHS of an assignment is not an lvalue. If it starts out as an lvalue, then lvalue conversion is applied. Logically the value is retrieved *and then* copied into the destination object. A simple case like this is not likely to cause problems (in the absence of agressive optimization), but we can construct more problematic cases where the object being copied is arbitrarily large and the overlap might not be detectable at compile time. I've written an answer: https://stackoverflow.com/a/65080498/827263 -- Keith Thompson (The_Other_Keith) Keith.S.Thompson+u@gmail.com Working, but not speaking, for Philips Healthcare void Void(void) { Void(); } /* The recursive call of the void */