Multiplying two shorts...

T. William Wells bill at proxftl.UUCP
Fri Aug 12 22:37:48 AEST 1988


In article <8101 at alice.UUCP> ark at alice.UUCP writes:
: In article <948 at srs.UUCP>, dan at srs.UUCP writes:
:
: > Sun's compilers seem to let you multiply two short integers and get all
: > 32 product bits, if you code like this:
: >     register short x, y;
: >     register long z;
:
: >     z = x * y;
:
: > If the compiler is nice, it emits the correct (16x16=32) multiply instruction.
: > If it isn't nice, it emits the slower (32x32=64) instruction and throws
: > away the top 32 bits.
:
: > Do most modern compilers perform this optimization?
: > It would be nice to be able to depend on it.
:
: The effect of the statment above is undefined.

That is not true.  The bit of code above is equivalent to:

	register short x, y;
	register long z;
	int     tmp1;
	int     tmp2;
	int     tmp3;

	tmp1 = (int)x;
	tmp2 = (int)y;
	tmp3 = tmp1 * tmp2;
	z = (long)tmp3;

What this means is that if the product of the values of the two
shorts will fit in an int, the code will work as expected.  If
not, then the result IS undefined.  To make this statement work
do:

:       z = (long) x * y;

as suggested.  And, as long as the product of the two shorts will
fit in a long, this will work.


---
Bill
novavax!proxftl!bill



More information about the Comp.lang.c mailing list