Shifting question
Guy Harris
guy at gorodish.Sun.COM
Thu Jul 21 14:59:06 AEST 1988
> | > 3.3.7 Bitwise shift operators
> | > ...If the value of the right operand is negative or is greater than or
> | > equal to the width in bits of the promoted left operand, the behavior
> | > is undefined.
> So you have to build in an explicit check in every program, comparing
> the shift with the size of the item.
No, you don't. You only have to build in explicit checks where "the value of
the right operand" could be "negative or ... greater than or equal to the
width in bits of the promoted left operand." For instance, an explict check
would be a waste of time in
#define NTH_BIT(bitarray, n) (bitarray[(n)/32] & (1 << ((n)%32))
since you already *know* that the RHS of the << is between 0 and 31 (we presume
here that "bitarray" is an array of 32-bit integral quantities). Similarly,
you don't need it for
nblocks = nbytes >> LOG2_BYTESPERBLOCK
if LOG2_BYTESPERBLOCK is a manifest constant that you know will be in the right
range.
I have run into only *one* piece of code where the fact that shifts of an
amount greater than the number of bits in the object is undefined caused
anything to break. It was a nuisance, but the code in question was commented,
and had an #ifdef for one processor with this characteristic; I had to add two
more (SPARC and 80386). I can live with that.
> If I sound really disgusted about this, I am. Compilers on brain
> damaged hardware should work correctly.
So if you feel so strongly about it, *lobby the ANSI C people* (as I've already
suggested); if you don't get them to change, you're not going to get everybody
to change their compilers. (If they say "no", perhaps they have good reasons
for saying so, so "I've already tried lobbying them" may not be a valid
response.)
As for what is or isn't "brain-damaged hardware", I'll let hardware designers
speak for whether there's any performance advantage to, say, using the shift
count modulo 32 rather than looking at it all.
And as for "correctly", this is a matter of opinion; the only thing close to an
*objective* definition for "correct" behavior of a C compiler is a C language
spec, and neither K&R nor current ANSI C drafts specify what is and what isn't
"correct" behavior here.
More information about the Comp.lang.c
mailing list