Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Posting-Version: version B 2.10.1 6/24/83; site umcp-cs.UUCP Path: utzoo!watmath!clyde!burl!ulysses!allegra!mit-eddie!genrad!teddy!panda!talcott!harvard!seismo!umcp-cs!chris From: chris@umcp-cs.UUCP (Chris Torek) Newsgroups: net.lang.c Subject: Re: unions inside structures Message-ID: <2606@umcp-cs.UUCP> Date: Sat, 19-Jan-85 19:15:30 EST Article-I.D.: umcp-cs.2606 Posted: Sat Jan 19 19:15:30 1985 Date-Received: Mon, 21-Jan-85 02:45:59 EST References: <133@ISM780B.UUCP> <10975@watmath.UUCP> Organization: U of Maryland, Computer Science Dept., College Park, MD Lines: 51 Concerning the problem of ``invented names'': Suppose you need a structure to hold either a character/font pair, or an adjustment. Then you might write enum node_type { ntype_char, ntype_adjust }; struct char_node { char cn_char; char cn_font; }; struct node { enum node_type n_type; /* is it a char or an adjust? */ union { struct char_node un_char;/* value if char */ short un_adj; /* value if adjust */ } n_un; }; (Note the ``invented name'' n_un.) Then a reasonable compromise for accessing the fields of a struct node is to create the definitions #define n_char n_un.un_char #define n_adj n_un.un_adj You can then write put(np) struct node *np; { if (np->n_type == ntype_char) { select_font(np->n_char.cn_font); put_char(np->n_char.cn_char); } else do_adj(np->n_adj); } which makes the ``n_un.un'' part of each name vanish. Admittedly this has problems, but it can improve readability---and it requires no changes to the language. -- (This line accidently left nonblank.) In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7690) UUCP: {seismo,allegra,brl-bmd}!umcp-cs!chris CSNet: chris@umcp-cs ARPA: chris@maryland