Portable use of unions
Wm E. Davidsen Jr
davidsen at sixhub.UUCP
Tue Dec 5 11:59:35 AEST 1989
I recently got a complaint that one of my programs was non-portable
and wouldn't run under a certain compiler. I isolated a tiny fragment
which causes the error message, and would like to know if anyone can
explain why this doesn't work other than the compiler being broken.
================ 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
The next to last line (2nd assignment) is flagged with a message of
"conflicting use of union fields in a single statement." I tried it on
seven common compilers and they all liked it. The int value of the union
holds the subscript of the start of the string, while the pointer value
will hold the actual starting address. Obviously only one can be valid
at any given time.
I'm willing to be shown that there's a problem here, but only if
either K&R or ANSI says there is. I don't care if people have broken
compilers, that's their problem, right?
--
bill davidsen - sysop *IX BBS and Public Access UNIX
davidsen at sixhub.uucp ...!uunet!crdgw1!sixhub!davidsen
"Getting old is bad, but it beats the hell out of the alternative" -anon
More information about the Comp.lang.c
mailing list