我刚刚写了这些代码:
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:
即您的第一个表达式 (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/