C 中类型转换时的运算符优先级 [英] Operator precedence while type casting in C

查看:41
本文介绍了C 中类型转换时的运算符优先级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面这段代码给出了乘法的正确结果

The following piece of code gives the correct result for the multiplication

int var0 = 245895;
int var1 = 478565

long long val = 0;

val = (long long) var0 * var1;

但是这篇文章给出了错误的结果:

but this piece gives the incorrect result:

int var0 = 245895;
int var1 = 478565
long long val = 0;

val = (long long) (var0 * var1);

有人能帮我解释为什么吗?

Could anybody help me with why?

推荐答案

(long long) var0 * var1
~~~~~~~~~~~~~~~~
       1
~~~~~~~~~~~~~~~~~~~~~~~
           2

在上面的代码中,首先将var0强制转换为long long,然后乘法的结果将计算为long long没有溢出.实际上编译器将var1的类型从int隐式提升为long long.

In the above code, first var0 casts to long long, after that, the result of multiplication will be calculated as long long with no overflow. In fact compiler promotes the type of var1 from int to long long implicitly.

(long long) (var0 * var1)
            ~~~~~~~~~~~~~
                  1
~~~~~~~~~~~~~~~~~~~~~~~~~
           2

在第二个代码中,第一次乘法发生并且结果不适合 long 类型,因此之后的转换不再有用.它会转换之前溢出的数字.

In the second code, first multiplication occurs and the result doesn't fit in a long type, so the cast after that doesn’t help anymore. It casts the number that is overflow-ed before.

因此,第一个优于第二个以避免溢出.

Therefore, the first one is better than second one to avoid overflows.

这篇关于C 中类型转换时的运算符优先级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆