Portable use of unions

Julio Raposo ajr at inesc.UUCP
Tue Dec 5 20:46:08 AEST 1989


In article <203 at sixhub.UUCP>, davidsen at 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 at inesc, LISBOA, PORTUGAL)



More information about the Comp.lang.c mailing list