struct/union/pointer query (Why isn't this legal?)

Ron Widell ron at motmpl.UUCP
Thu Jul 13 02:01:30 AEST 1989


My apologies if the previous posting went out, I tried to cancel it.

In trying to understand how to define, declare and use structures, unions
and pointers to same, I hacked up the following piece of strange code.
Now, I know it's ugly, but I thought that it was legal, yet I can't get
any (SGS, Sun, TurboC, MSC) compiler to take it unless I define BURP before
trying to compile. As I interpret K&R, 1e (page 120 in particular); I
think it should be legal, so why won't any of the compilers I've tried
accept it? Could I be wrong and the whole world be right :-)?

#include <stdio.h>

main()
{
	union {
		unsigned short foo;
#ifdef BURP
		struct burp {
#else
		struct {
#endif
			unsigned char fuz;
			unsigned char bar;
			} baz, *sptr;
	} glorp, *uptr;
#ifdef BURP
	struct burp  baz, *sptr;
#endif

	uptr = &glorp;
	sptr = &glorp.baz;
	uptr->foo = (unsigned short)0x4142;
	(void)putchar((char)sptr->fuz);
	(void)putchar('\n');
	(void)putchar((char)sptr->bar);
	(void)putchar('\n');
	return 0;
}
 Here's the output from lint:

junk.c
==============
(22)  sptr undefined
warning: illegal combination of pointer and integer:
    (22)  operator =
warning: struct/union or struct/union pointer required
    (24)  	    (26)  	

and here's the output (stderr) from SGS cc:

"junk.c", line 22: sptr undefined
"junk.c", line 22: warning: illegal pointer/integer combination, op =
"junk.c", line 24: warning: struct/union or struct/union pointer required
"junk.c", line 24: warning: struct/union or struct/union pointer required
"junk.c", line 26: warning: struct/union or struct/union pointer required
"junk.c", line 26: warning: struct/union or struct/union pointer required

Well, at least they agree :-).

BTW #1- I know that the *code* is bogus and very nonportable, and probably
works only by accident. It's there *only* to give lint and cc something to
munch on. I'm only interested in the legality of the union{..struct{..};};
definition/declaration.

BTW #2- What I *think* I'm defining is a union with three members: 1) an
unsigned short (on the target machine it's an int). 2) a structure of 2
unsigned chars. 3) a pointer to a structure of 2 unsigned chars.

Please respond via e-mail, I will summarize. Flame as required.

Regards,
-- 
Ron Widell, Field Applications Eng.	|UUCP: {...}mcdchg!motmpl!ron
Motorola Semiconductor Products, Inc.,	|Voice:(612)941-6800
9600 W. 76th St., Suite G		| I'm from Silicon Tundra,
Eden Prairie, Mn. 55344 -3718		| what could I know?



More information about the Comp.lang.c mailing list