Article View: comp.std.c
Article #4173Re: Union access
From: Nick Maclaren
Date: Wed, 04 Oct 1995 13:01
Date: Wed, 04 Oct 1995 13:01
48 lines
2312 bytes
2312 bytes
In article <812736828snz@soliton.demon.co.uk>, Ian Cargill <ian@soliton.demon.co.uk> writes:
|> It has been asserted elsewhere by someone that:
|>
|> > "The only guarantee that C gives is that the following data
|> > structure can be written one way and read another."
|> >
|> > union {
|> > unsigned char a[4];
|> > int b;
|> > }
|>
|> I replied with my opinion that this is actually implementation defined
|> behavior, and that the only guarantee the standard gives is regarding
|> access to common initial sequences of structs in a union.
This is correct. The standard defines common initial sequences in terms
of compatibility (q.v.), and unsigned char[4] is definitely incompatible
with int. Unfortunately, there are some horrible ambiguities to do with
the concept of compatibility. Try the following for size:
union {
int *fred;
unsigned int *joe;
const int *alf;
/* And so on ... */
}
|> Since there is still some dispute, I would welcome comment from the
|> assembled multitude, particularly those who know what they are talking
|> about. A majority verdict will do. :-)
When talking on C, I use a related construction as an example of something
that is simultaneously illegal and required to work. I.e. a conforming
compiler may reject the program but, if it fails to detect the error, the
compiled code must execute correctly.
There is actually some dissent about this. Some people hold the view that
implementation-defined behaviour allows the compiler writer to say "if you
use this construction, you will get no error message and your program will
go bananas." This is clearly not what the ANSI committee intended compiler
writers to do :-)
Nick Maclaren,
University of Cambridge Computer Laboratory,
New Museums Site, Pembroke Street, Cambridge CB2 3QG, England.
Email: nmm1@cam.ac.uk
Tel.: +44 1223 334761 Fax: +44 1223 334679
Technical Details
Message-ID:
<44u0jm$9pr@lyra.csx.cam.ac.uk>Path:
arc1-ca.pugleaf.net!lyra.csx.cam.ac.uk!nmm1References:
<812736828snz@soliton.demon.co.uk>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!lyra.csx.cam.ac.uk!nmm1 From: nmm1@cus.cam.ac.uk (Nick Maclaren) Newsgroups: comp.std.c Subject: Re: Union access Date: 4 Oct 1995 13:01:42 GMT Organization: University of Cambridge, England Message-ID: <44u0jm$9pr@lyra.csx.cam.ac.uk> References: <812736828snz@soliton.demon.co.uk> NNTP-Posting-Host: ursa.cus.cam.ac.uk