Path: csiph.com!weretis.net!feeder6.news.weretis.net!news.misty.com!news.iecc.com!.POSTED.news.iecc.com!nerds-end From: David Brown Newsgroups: comp.compilers Subject: Re: Union C++ standard Date: Sat, 27 Nov 2021 16:59:36 +0100 Organization: A noiseless patient Spider Lines: 24 Sender: news@iecc.com Approved: comp.compilers@iecc.com Message-ID: <21-11-008@comp.compilers> References: <21-11-004@comp.compilers> Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: 8bit Injection-Info: gal.iecc.com; posting-host="news.iecc.com:2001:470:1f07:1126:0:676f:7373:6970"; logging-data="50781"; mail-complaints-to="abuse@iecc.com" Keywords: C, standards Posted-Date: 27 Nov 2021 14:29:18 EST X-submission-address: compilers@iecc.com X-moderator-address: compilers-request@iecc.com X-FAQ-and-archives: http://compilers.iecc.com In-Reply-To: <21-11-004@comp.compilers> Content-Language: en-GB Xref: csiph.com comp.compilers:2755 On 25/11/2021 11:11, Hans-Peter Diettrich wrote: > Can somebody explain why the access to members of a union is "undefined" > except for the most recently written member? > > What can be undefined in a union of data types of the same typesize end > alignment? Any member written will result in a unique bit/byte pattern > in memory, whose reading may not make sense in a different type but > undoubtedly is well defined. > > DoDi > [I think it's undefined in a standards sense.  In any individual > implementation the result is predictable, but it's not portable. -John] > In C++, objects of a class typically have some kind of invariant which is established by the constructor, and kept consistent when accessed via its public methods. Messing with the underlying data representation directly is going to risk losing that - it means you are accessing data without going through the proper defined interface (the public or protected methods and members). In C, type-punning via unions is allowed (i.e., fully defined behaviour in the standards), but not in C++ where the language is expected to enforce higher-level aspects of the data.