Re: Union C++ standard

David Brown <david.brown@hesbynett.no>
Sat, 27 Nov 2021 16:59:36 +0100

          From comp.compilers

Related articles
Union C++ standard DrDiettrich1@netscape.net (Hans-Peter Diettrich) (2021-11-25)
Re: Union C++ standard 480-992-1380@kylheku.com (Kaz Kylheku) (2021-11-26)
Re: Union C++ standard gah4@u.washington.edu (gah4) (2021-11-26)
Re: Union C++ standard david.brown@hesbynett.no (David Brown) (2021-11-27)
Re: Union C++ standard derek@NOSPAM-knosof.co.uk (Derek Jones) (2021-11-28)
Re: Union C++ standard david.brown@hesbynett.no (David Brown) (2021-11-28)
Re: Union C++ standard derek@NOSPAM-knosof.co.uk (Derek Jones) (2021-11-29)
Re: Union C++ standard 480-992-1380@kylheku.com (Kaz Kylheku) (2021-11-29)
Re: Union C++ standard david.brown@hesbynett.no (David Brown) (2021-11-29)
Re: Union C++ standard Keith.S.Thompson+u@gmail.com (Keith Thompson) (2021-11-29)
[4 later articles]
| List of all articles for this month |
From: David Brown <david.brown@hesbynett.no>
Newsgroups: comp.compilers
Date: Sat, 27 Nov 2021 16:59:36 +0100
Organization: A noiseless patient Spider
References: 21-11-004
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
In-Reply-To: 21-11-004
Content-Language: en-GB

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.


Post a followup to this message

Return to the comp.compilers page.
Search the comp.compilers archives again.