enum, bit fields, cpp...

turner at ucbesvax.UUCP turner at ucbesvax.UUCP
Fri Mar 2 16:41:00 AEST 1984


/* C hackers: why does this abort?  (Don't peek at the answer below.)	*/
typedef enum {False, True} bool;

main() {		/*       note the single-bit-field below */
	struct { bool flag : 1; } var;

	var.flag = True;
	if (var.flag != True ) abort ( );
}
/*	*	*	*	*	*	*	*	*	*/

Give up?  Well, except for type-checking, enum bools "are treated as if
they were int" [1] in the Ritchie C compiler; this is the only guideline
on the question of enum signedness.  The single-bit field may or may not
be considered signed [2].  If it is signed, the flag bit is read out and
sign-extended.  For 4.2 BSD pcc, var.flag == (bool) (-1).  Now try

	    if ( (var.flag = True) != True) abort ( );

With 4.2 pcc, this doesn't abort--I suppose because the compiler is "smart"
about assigning constants and then comparing results within a certain window.

If you are a crypto-Wirthite strong-typing warrior in the Jihad against
Dangerous and Sacrilegious Programming Styles (like me), I highly recommend
using one of the following forms for Boolean typedefs:

/*	*	*	*	*	*	*	*	*	*/
#if pdp11 || ...	/* ... any machine with unsigned bit-fields	*/
#define __TRUE__ 1	/* non-sign-extended TRUE			*/
#else
#define __TRUE__ (-1)	/* sign-extended TRUE				*/
#endif

typedef enum {TRUE=__TRUE__, FALSE=0} bool;	/* crypto-Wirthite	*/
typedef enum {true=__TRUE__, false=0} Boolean;	/* Fundamentalist	*/
/*	*	*	*	*	*	*	*	*	*/

A suggestion to the C ANSI standards committee: to the extent that they are
defining the C preprocessor, I would like to see __TRUE__ available from cpp,
rather than be forced to use "#if this-machine-or-that" hacks.

This form could extend to any machine dependency allowed by the prevailing
language definition.  I would, for the example above, happily settle for the
having __UBITFIELD__ auto-defined when bit fields are always unsigned; maybe
we could have __SCHAR__ for when there is no unsigned char, __CHARSX__ for
when char always gets sign-extended, and so on.  The "compiler control
lines" have a bastard status within the language definition.  Perhaps in
formalizing it, some of these issues could be addressed.

Living on the west coast, I can't make it to *one* ANSI committee meeting,
much less two in a row.  Perhaps someone with a vote there could bring this
issue up for me?
---
[1] "Recent Changes to C", D. M. Ritchie, Nov 15, 1978.
[2] "The C Programming Language--Reference Manual", D. M. Ritchie, p. 13.
---
Michael Turner (ucbvax!ucbesvax.turner)



More information about the Comp.lang.c mailing list