Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!cs.utexas.edu!samsung!emory!cambridge.apple.com!bloom-beacon!eru!luth!sunic!mcsun!inesc!ajr From: ajr@inesc.UUCP (Julio Raposo) Newsgroups: comp.lang.c Subject: Re: Portable use of unions Summary: an explanation Keywords: unions Message-ID: <154@inesc.UUCP> Date: 5 Dec 89 09:46:08 GMT References: <203@sixhub.UUCP> Organization: INESC - Inst. Eng. Sistemas e Computadores, LISBOA. PORTUGAL. Lines: 49 In article <203@sixhub.UUCP>, davidsen@sixhub.UUCP (Wm E. Davidsen Jr) writes: > > ================ start code > > /* test of code generated for unions */ > > char buf[30]; /* simple char buffer */ > > union { > int t_sscr; /* subscript of location */ > char *t_adrs; /* actual location */ > } demo; > > main() { > demo.t_sscr = 4; > demo.t_adrs = &buf[demo.t_sscr]; > } > > ================ end code > This code is non-portable because in the C language the evaluation order is undefined. The compiler may evaluate first demo.t_adrs and when it tries to evaluate demo.t_sscr complains that the address is already beeing used. For that example I would write: (coments erased) ================ start code char buf[30]; union { int t_sscr; char *t_adrs; } demo; main() { char *aux; demo.t_sscr = 4; aux = &buf[demo.t_sscr]; demo.t_adrs = aux; } ================ end code Antonio Julio Raposo (ajr@inesc, LISBOA, PORTUGAL)