gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 19:44:15 28 4
gpt4 key购买 nike

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

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

If none of the floating-point promotion rules apply, you then checkwhether either argument is signed. If so, both operands become signed.Finally, as with the promotion rules for floating-point types, the size of thelargest 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com