Path: utzoo!utgpu!water!watmath!clyde!att!osu-cis!tut.cis.ohio-state.edu!mailrus!cornell!uw-beaver!uw-june!pardo From: pardo@june.cs.washington.edu (David Keppel) Newsgroups: comp.lang.c Subject: Re: Unions Keywords: What can they be used for? Message-ID: <6176@june.cs.washington.edu> Date: 22 Oct 88 02:40:06 GMT References: <322@hrc.UUCP> <2699@hound.UUCP> <976@l.cc.purdue.edu> <14103@mimsy.UUCP> Reply-To: pardo@cs.washington.edu (David Keppel) Organization: U of Washington, Computer Science, Seattle Lines: 63 In article <14103@mimsy.UUCP> chris@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@cs.washington.edu {rutgers,cornell,ucsd,ubc-cs,tektronix}!uw-beaver!june!pardo