Multiplying two shorts...
ark at alice.UUCP
ark at alice.UUCP
Thu Aug 11 12:34:55 AEST 1988
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.
To get the right answer, you should write
z = (long) x * (long) y;
Actually, it is enough to cast only one of x and y, so you
can say
z = (long) x * y;
but that may be a little confusing. If your compiler is clever,
it will realize that it can use the multiply instruction that
takes short operands into a long result. If it's not clever,
you'll still get the right answer.
Wouldn't you rather risk having your program get the right answer
slowly rather than risk getting the wrong answer outright?
More information about the Comp.lang.c
mailing list