Article View: comp.std.c
Article #4171Re: Union access
From: Stephen Baynes
Date: Wed, 04 Oct 1995 07:29
Date: Wed, 04 Oct 1995 07:29
40 lines
2246 bytes
2246 bytes
Ian Cargill (ian@soliton.demon.co.uk) wrote:
: 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.
: 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. :-)
I would not like to say it even gives that guarantee. I think you can
say you can write .b and read .a (though what is read is useless). I am
not sure that you can write .a and read .b as I am not sure if it is
guaranteed that all combinations of the bits of the machine representation
are legitimate integer values or if some can lead to undefined behaviour
(eg a parity check failure). (It is the case that not all the bits have to
be used as part of the integer value.) However I do recall some argument that
all bit combinations must give as defined behaviour (though implementation
defined) as a _valid_ integer. In this case you can read and write either
way (though neither is useful).
If you changed a to be a[sizeof(int)] then you could (I think) guarantee that
copying to another variable of the union type then you would have copied the
value of b too.
--
Stephen Baynes baynes@mulsoc2.serigate.philips.nl
Philips Semiconductors Ltd
Southampton My views are my own.
United Kingdom
Technical Details
Message-ID:
<DFwy5I.7HF@ukpsshp1.serigate.philips.nl>Path:
arc1-ca.pugleaf.net!phcoms4.seri.philips.nl!panther!baynesReferences:
<812736828snz@soliton.demon.co.uk>Show Full Headers
Complete Article Headers
Newsgroups: comp.std.c Path: arc1-ca.pugleaf.net!phcoms4.seri.philips.nl!panther!baynes From: baynes@ukpsshp1.serigate.philips.nl (Stephen Baynes) Subject: Re: Union access Sender: news@ukpsshp1.serigate.philips.nl (account for localnews) Message-ID: <DFwy5I.7HF@ukpsshp1.serigate.philips.nl> Date: Wed, 4 Oct 1995 07:29:42 GMT References: <812736828snz@soliton.demon.co.uk> Organization: Philips Semiconductors, Southampton, UK X-Newsreader: TIN [version 1.2 PL2]