Of Standards and Inventions: A Cautionary Tale

Walter Bright bright at Data-IO.COM
Wed Apr 13 03:59:51 AEST 1988


In article <1758 at ur-tut.UUCP> joss at tut.cc.rochester.edu (Josh Sirota) writes:
>In article <10353 at steinmetz.ge.com> davidsen at crdos1.UUCP (bill davidsen) writes:
>>With programs traveling between 32 bit machines and 16 bit machines
>>(286, 11s) I want to say:
>>	#if	sizeof int < 32
>>	#define INT	long
>>	#else
>>	#define INT	int
>>	#endif
>Why would you want to do this?  If you want 4 byte values, specify long
>on ANY machine.

Here is a portion of a package to handle bit vectors in C. It demonstrates
a reasonable use for allowing casts and sizeofs in preprocessor expressions.
----------------------------------------------------------------
/* Use base type that is probably the most efficient for this machine	*/
#define vec_t unsigned		/* preprocessor can't see typedefs	*/

/* This code depends on 8 bit bytes. Put check in for this.	*/
/* I don't care about 1's complement machines.			*/
#if (unsigned char) -1 != 255
#error	"bytes are not 8 bits"
#endif

#define BITSPERBYTE 8

#define VECMASK	(sizeof(vec_t)*BITSPERBYTE - 1)	/* mask for bit position */

/* Determine VECSHIFT, the number of bits set in VECMASK.	*/
/* If anyone knows a nifty way to convert from VECMASK to	*/
/* VECSHIFT, in such a way that VECSHIFT is a constant that	*/
/* can be folded with others, please send me mail!		*/
#if sizeof(vec_t) * BITSPERBYTE == 16
#define VECSHIFT 4
#elif sizeof(vec_t) * BITSPERBYTE == 32
#define VECSHIFT 5
#else
#error	"need to fix this"
#endif

void vec_setbit(b,v)	/* Set bit b in vector v	*/
unsigned b;
vec_t *v;
{
  *(v + (b >> VECSHIFT)) |= 1 << (b & VECMASK);
}



More information about the Comp.lang.c mailing list