Przemek Klosowski wrote:
Cast /one/ operand to 32 bits before multiplication and prey for that
you don't have a really bad compiler. GCC should infer a 16Bit*16Bit =>
32Bit multiplication. IAR does the same
I think that means that IAR is not ANSI C conformant, because for better
or worse ANSI specifies the type promotion so that it forces a 32x32->32
operation here.
First of all: msp430-gcc and IAR have the same behavior
my_long = (long)my_int_a * my_int_b; -- 32bit = 16bit * 16bit;
But is this a violation of the standard? I don't think so. If there is a
cast of one operand to type long the compiler shall promote the other
operand too, because arithmetics shall always use the "bigger" type. Up
to here I agree with you. But after this the compiler is free to
optimize everything away that is not needed to get a mathematically
correct result. For the multiplication this means, that the upper 16
Bits of the two operands are not needed for a 32 bit wide result.
Therefore the compiler is free to reduce the multiplication to a
16bit*16bit one.
Using these thoughts one could say, that
my_long = (long)my_int_a * (long)my_int_b;
should do the same, because again the compiler is free to reduce the
multiplication bitwidth. But unfortunately the compiler is just a
machine and optimization of arithmetic therms is not its main target.
(It would be great, if the compiler would do it, but it is not state of
the art.) Therefore the user has to give the compiler a hint and this
hint is the rule: "cast only one operand of the multiplication to the
target bitwidth".
Ralf