Two Birds with One Stone

Walter Bright bright at dataioDataio.UUCP
Wed Dec 11 04:02:09 AEST 1985


In article <119 at hadron.UUCP> jsdy at hadron.UUCP (Joseph S. D. Yao) writes:
>I believe that this falls under the heading, "say what you mean."
>If you  m e a n  that bits should shift left, say so; if you instead
>m e a n  that you wish to multiply (resp., divide); say that, also!
>Your compiler (at least, with optimisation on) should be able to do
>the conversion if it speeds anything up.

Almost but not quite true. A compiler CANNOT normally replace a divide
by a right-shift if it is an integer divide. This is because a right
shift of a negative integer is not the same as a divide.

	{	int i;
		unsigned u;

		i *= 4;		==>	i <<= 2;
		u *= 4;		==>	u <<= 2;
		i /= 4;		==>	i >>= 2;	WRONG!
		u /= 4;		==>	u >>= 2;
	}

Since divides are relatively expensive, one would want them replaced
by shifts whenever possible. The only way you can get the compiler
to do this is by casting the int to unsigned before the divide is done
(but check the output of the compiler to make sure it is doing things
correctly).



More information about the Comp.lang.c mailing list