0

我想知道,当两个整数相乘并将结果类型转换为short并分配给short时,编译器会将其解析为什么?下面是代码片段

int a=1,b=2,c;
short x=3,y=4,z;

int p;
short q;

int main()
{

c = a*b; /* Mul two ints and assign to int
            [compiler resolves this to __mulsi3()] */

z = x*y; /* Mul two short and assign to short
            [compiler resolves this to __mulhi3()] */

p = (x*y); /* Mul two short and assign to int
              [compiler resolves this to __mulsi3()] */

q =(short)(a*b); /* Mul two ints typecast to short and assign to short
                    [compiler resolves this to __mulhi3()] */

return 0;

} 

在 for 的情况下q =(short)(a*b);,应该执行前两个整数乘法(使用__mulsi3()),然后将其分配给 short。但这里不是这种情况,编译器类型将两者都转换为ab,然后调用__mulhi3().

我想知道如何更改 gcc 源代码 [哪个文件],以便我可以实现上述要求。

4

1 回答 1

0

编译器可以分析代码并看到当您立即将结果转换为 ashort时,可以将乘法作为乘法来完成,short而不会影响结果。这与您的示例的情况二完全相同。

结果是一样的,你不必担心使用哪个乘法函数。

于 2012-06-29T05:26:53.213 回答