gpt4 book ai didi

C常用的算术转换

转载 作者:太空狗 更新时间:2023-10-29 16:53:05 25 4
gpt4 key购买 nike

我正在阅读有关常用算术转换的 C99 标准。

If both operands have the same type, then no further conversion is needed.

Otherwise, if both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank is converted to the type of the operand with greater rank.

Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type.

Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, then the operand with unsigned integer type is converted to the type of the operand with signed integer type.

Otherwise, both operands are converted to the unsigned integer type corresponding to the type of the operand with signed integer type.

假设我有以下代码:

#include <stdio.h>

int main()
{
unsigned int a = 10;
signed int b = -5;

printf("%d\n", a + b); /* 5 */
printf("%u\n", a + b); /* 5 */
return 0;
}

我认为粗体段落适用(因为 unsigned intsigned int 具有相同的等级。为什么 b 不转换为 unsigned ? 或者它可能已转换为无符号但有一些我不明白的东西?

感谢您的宝贵时间:-)

最佳答案

确实b转换为unsigned。然而,您观察到的是 b 转换为无符号然后添加到 10 给出值 5。

在 x86 32 位上会发生这种情况

  1. b,转换为 unsigned,变为 4294967291(即 2**32 - 5)
  2. 由于在 2**32 处回绕,加 10 变为 5 (2**32 - 5 + 10 = 2**32 + 5 = 5)

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

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