"for" loops in C ...

Richard A. O'Keefe ok at quintus.uucp
Wed Nov 9 14:19:07 AEST 1988


In article <339 at igor.Rational.COM> dsb at Rational.COM (David S. Bakin)
continues asking about "<<".
>The operator << is defined in C as a left shift, ...

Nope.  << is defined to be whatever C defines it to be, and C leaves it
as vague as possible to make it easy for compiler writers to generate
fast code.  (There is something just slightly crazy about this.)  It has
nothing to do with the VAX as such.  We can define shifting for signed
integers as
	X << Y = floor(X * 2**Y)
which definition works beautifully for all values of X and Y.  Alas,
that's not what the hardware does on _any_ machine that I know of (the
VAX comes *closest*.)  Some machines take the bottom 5 bits.  Some take
the bottom 6.  Some haven't _got_ a left shift instruction.  (For
example, on the M88000, the simplest translation of X<<Y yields the
result X&1 when Y==32.)

If you want to make sure that you will get the result you expect,
define BITS_PER_BYTE suitably and write
	result = Y >= BITS_PER_BYTE*sizeof X ? 0 : X>>Y;
(assuming that you are happy to have result undefined when Y < 0).



More information about the Comp.lang.c mailing list