c++ - 为什么 ((unsigned int)x) * y == ((unsigned int)(x * y) 总是为真?

标签 c++ implicit-conversion

我刚刚写了这些代码:

int x = -1;//x must be negative
unsigned int y = 1;//y must be positive
bool b;
for(; ; x--, y++){
    b = ((unsigned int)x) * y == ((unsigned int)(x * y));
}

然后我才发现b总是为真。在我看来,((unsigned int)x) * y 会溢出,但 ((unsigned int)(x * y)) 不会。我真的很难相信这是真的。这只是巧合还是有一定规律可循?

最佳答案

x * y 中,x 作为通常算术转换的结果已经转换为 unsigned。 §5/10:

enter image description here

即您的第一个表达式 (unsigned)(x * y) 等效于 (unsigned)((unsigned)x * y) 而后者又等效于 (unsigned)x * y - 你的第二个表达式。


请注意,根据 §4.13/1.4,unsigned int 的等级等于 (signed)int 的等级:

The rank of any unsigned integer type shall equal the rank of the corresponding signed integer type.

关于c++ - 为什么 ((unsigned int)x) * y == ((unsigned int)(x * y) 总是为真?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31702505/

相关文章:

c++ - 如何在 Visual Studio (C++) 中设置发布分析

c++ - 在c++中搜索和替换txt文件中的字符串

c++ - 简单的 C++ 多线程示例未在 CentOS Linux 中编译

c++ - 将显式实例化的函数模板与转换相匹配

c++ - std::string const& 参数是否复制传递的 const char* ?

c++ - 隐式类型转换表现得很奇怪

有人可以解释为什么我的第一个打印 0,但在 *p = 6.35 之后,它可以打印 6.35?

c# - 卸载 appdomain 不清除 C++ COM 对象静态成员

c++ - 从函数返回多维 vector 供main使用,如何正确使用?

c++ - 在 C/C++ 中从 double 到 int64_t 的隐式转换是什么