C++ 常见的算术转换不转换

标签 c++

首先,我想指出,我确实阅读了一些标题大致相似的其他答案。然而,这些要么是指我认为是旧版本的标准,要么是处理促销,而不是转换。

我一直在浏览“C++ 速成类(class)”,其中作者在探索内置运算符的章节中指出了以下内容:

If none of the floating-point promotion rules apply, you then check whether either argument is signed. If so, both operands become signed. Finally, as with the promotion rules for floating-point types, the size of the largest operand is used to promote the other operand: ...

如果我正确地阅读了标准,则事实并非如此,因为根据 cppreference.com,

If both operands are signed or both are unsigned, the operand with lesser conversion rank is converted to the operand with the greater integer conversion rank

Otherwise, if the unsigned operand's conversion rank is greater or equal to the conversion rank of the signed operand, the signed operand is converted to the unsigned operand's type.

Otherwise, if the signed operand's type can represent all values of the unsigned operand, the unsigned operand is converted to the signed operand's type

Otherwise, both operands are converted to the unsigned counterpart of the signed operand's type.

更让我困惑的是以下代码:

printf("Size of int is %d bytes\n", sizeof(int));
printf("Size of short is %d bytes\n", sizeof(short));
printf("Size of long is %d bytes\n", sizeof(long));
printf("Size of long long is %d bytes\n", sizeof(long long));
unsigned int x = 4000000000;
signed int y = -1;
signed long z = x + y;
printf("x + y = %ld\n", z);

产生以下输出:

Size of int is 4 bytes
Size of short is 2 bytes
Size of long is 8 bytes
Size of long long is 8 bytes
x + y = 3999999999

据我了解标准,y 应该已转换为 unsigned int,从而导致错误的结果。结果正确的,这使我假设在这种情况下没有发生转换。为什么?对于此事的任何澄清,我将不胜感激。谢谢。

(我也很感激有人告诉我,我在现实生活中永远不需要这种神秘的知识,即使这不是真的 - 只是为了内心的平静。)

最佳答案

将负有符号值转换为无符号值会得到与其对应的二进制补码值。添加此无符号值将导致溢出,从而产生与添加负值完全相同的值。

顺便说一句:这就是处理器进行减法的技巧(或者在现代我错了?)。

关于C++ 常见的算术转换不转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60226543/

相关文章:

c++ - 如果只有 std::auto_ptr 可用,我还应该使用智能指针吗?

c# - C、C++、C# 的功能测试工具

c++ - 将迭代器移动 N 次 C++

c++ - copy_backward 和 reverse_copy 之间的区别?

c++ - 添加自定义稀疏操作(稀疏行列式)

c++ - boost::asio::read() 永远阻塞

c++ - 具有继承性的数据结构。初始化问题

c++ - Mac错误: Undefined symbols for architecture x86_64

c++ - 使用 STL 算法合并 2 个 vector

C++ 图像处理 - 将图像文件读入二维数组