Multiplying two shorts...

Radford Neal radford at calgary.UUCP
Sun Aug 14 06:50:57 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;

In article <8101 at alice.UUCP>, ark at alice.UUCP writes:

> The effect of the statment above is undefined.
> 
> To get the right answer, you should write
> 
> 	z = (long) x * (long) y;
> ...
> Wouldn't you rather risk having your program get the right answer
> slowly rather than risk getting the wrong answer outright?

In article <864 at l.cc.purdue.edu>, cik at l.cc.purdue.edu (Herman Rubin) writes:

> It is a rare compiler which can recognize that it can ignore type
> casting and use a different instruction to get a result.  It is hard
> enough to get a compiler to do the obvious.  I find the attitude of
> "ark" execrable...

Very puzzling. Why is informing people that their programs may break
when moved to another compiler such a crime? If you want to argue that
the C language _ought_ to be defined so that the product of two shorts
is computed to long precision, that's another issue, though some might
object to the code this would imply for:

       int a, b, c, d;

       a = (a*b*c*d) % 10;

By your logic, the intermediate result (a*b*c*d) should be computed to
128-bit precision, assuming int's are 32 bits.

> We need software which allows those who understand their machine to exploit
> the capabilities.

We already have such software. It's called an assembler.

> We need hardware which provides the capabilities...

If you're willing to pay enough, I'm sure someone will oblige. Actually, 
your best bet in this case would seem to be RISC machines with software
multiplication and division, then you can do whatever you want.

> We do not need to be told that "this is not portable; you must not do it."

Any professional programmer ought to realize when a programming technique
is not portable. Whether they choose to do it anyway is another matter.

In fact, "ark" was arguing that including casts got you both - a portable
program, and a fast one if the compiler is smart. Contorting your program
to get fast code out of dumb compilers is a technique of limited usefullness.

     Radford Neal



More information about the Comp.lang.c mailing list