Unions

David Keppel pardo at june.cs.washington.edu
Sat Oct 22 12:40:06 AEST 1988


In article <14103 at mimsy.UUCP> chris at mimsy.UUCP (Chris Torek) writes:
>[ register unions ]
>There *are* compilers that do it right.  (Does GCC?)

Lint(1) complains about the construct "register union" when you try to
access a field of it.

Gcc (the GNU project C compiler) gets this right, however, even in the
case where you have (say) array components as part of the union:

    union u{
	int x;
	char y[2];
    };

	union u
    foo (x)
	int x;
    {
	register union u splat;

	splat.x = x + 2;
	(void)printf ("splat %d\n", splat.x);
	splat.y[0] = 'c';
	splat.y[1] = 'd';
	return splat;
    }

The resulting VAX code is:

    #NO_APP
    .text
	    .align 0
    LC0:
	    .ascii "splat %d\12\0"
	    .align 1
    .globl _foo
    _foo:
	    .word 0x40
	    addl3 4(ap),$2,r0		# put union in register
	    movl r0,r6			# save value of union
	    pushl r0
	    pushab LC0
	    calls $2,_printf
	    movb $99,r6			# splat.y[0] = 'c'
	    insv $100,$8,$8,r6		# splat.y[1] = 'd'
	    movl r6,r0
	    ret

Interesting note: gcc preserves the high-order bits of the union.
I believe that this behavior is not guaranteed either by K&R or by the
dpANS proposed standard.  (Anybody know?  Tell me, please?)

Note also that gcc puts the union in the register even if you don't
ask it to, and if you take the address of it it will spill the value
to the stack (rather than performing all operations on the stack).
The union return value is returned in a register, I believe that
there is a flag to force return it on the stack.

	;-D on  ( A Programmer's Union )  Pardo
-- 
		    pardo at cs.washington.edu
    {rutgers,cornell,ucsd,ubc-cs,tektronix}!uw-beaver!june!pardo



More information about the Comp.lang.c mailing list