[Icc-avr] Packing of variables in union

John Baraclough j_baraclough at zetnet.co.uk
Fri May 18 15:00:40 PDT 2007


Hi Johan,

Sorry, but that is very bad programming practice.

K&R states: "It is the responsibility of the programmer to keep track 
of what type is currently stored in a union; the results are machine 
dependent if something is stored as one type and extracted as another."

Thus writing:

u.w16 = 123;
c = u.b8;

may not return the expected value of 123 into 'c'. Furthermore, it is 
unsafe to assume that what works in one release will also work in the 
next. I'm sure that Richard will try his utmost to retain reverse 
compatibility, but K&R does not require it.

HTH.

All the best for now,
John


At 20:47 18/05/2007, you wrote:
>Hi,
>
>can I trust ICCAVR to *always* put all members of a union at
>the same starting address?
>
>Example:
>   given the following declaration:
>
>union
>{
>   short w16;
>   char b8;
>   long l32;
>   char abFourBytes[4];
>   char abSevenBytes[7];
>} u;
>
>is this true:
>
>   b8 == (w16 & 0xFF) == (l32 & 0xFF) == abFourBytes[0] == abSevenBytes[0] ?
>
>I have in some dull memory that alignment in struct and union is allowed
>to be "impementation dependent" but I can see no reason use other than
>8-bit alignment (== no "padding") in the AVR (?).
>
>I don't have my trusty old K&R at hand right now so I can't check the rules...
>
>
>Regards
>Johan Bodin, SM6LKM
>
>_______________________________________________
>Icc-avr mailing list
>Icc-avr at imagecraft.com
>http://dragonsgate.net/mailman/listinfo/icc-avr
>




More information about the Icc-avr mailing list