C pet peeve - (nf)

utzoo!decvax!harpo!eagle!allegra!princeto!leei utzoo!decvax!harpo!eagle!allegra!princeto!leei
Wed Mar 23 12:17:42 AEST 1983


	As long as pet peeves with C are the vogue, my personal pet peeve is
the fact that C's union construction necessarily introduces an extra level
of context.  I always wanted to be able to set up structures like:

struct foo {
    short type;
    union {
	int as_int;
	char *as_ptr;
    };
} bar;

and then be able to use it like:

	if ( bar.type == INTEGER )
	    printf("%d", bar.as_int);
	else
	    printf("%s", bar.as_ptr);

As it is now, I have to either name the union inside and specify the union
name in the path, or use #define's to avoid having to specify this spurious
node.

	Well, you say, too bad but what can we do?  It's actually pretty easy.
A friend of mine and I hacked Steve Johnson's PCC, which makes up pass 1 of the
UNIX C compiler (at least for 4.1, I'm not sure about the others).  We changed
the structure dereferencing so that it does a search down the structure tree
until it finds the element you asked for.  Admittedly, this is not the most
direct solution to the problem, since I would much rather be able to use an
overlay structure which simply overlays storage without adding another level
of context, but this was much easier to do (and somewhat more general).

	With our hack, we can do things like that seen below.

struct a {
    int s;
    union {
	int b;
	char c;
	char *s;
    } o;
} glumph;

and 'glumph.s' refers to the outer level integer
    'glumph.o.s' refers to the inner level char pointer
    'glumph.b' refers to the \inner/ level integer 
    'glumph.c' refers to the \inner/ level char

	We now have a copy of our new ccom in my bin, which we both use for
our useless little hacks.  It should be pointed out that changes like this 
are COMPLETELY NON-PORTABLE and are not really recommended, even when they
work.  What we will do is use this for development and then clean up after
ourselves afterwards.  The point is, I don't like the way C handles this and
something can be done about it on a local level.  If anyone is stupid enough,
I can mail them a diff on cgram.y, which is where we made the change.

	I'm really not too happy about this, it's just too much of a hack, and
I would much prefer to implement the 'overlay' construct, which would take the
form of a union with no context level change, but it would HAVE to be inside
a struct, and it appears that it would take quite a bit of substantial hacking
at cgram.y.  Good luck if you want to try it.

						Lee Iverson
						princeton!leei



More information about the Comp.lang.c mailing list