gpt4 book ai didi

c++ - 为什么(-i)的类型,其中i是unsigned int,还是unsigned int?

转载 作者:太空宇宙 更新时间:2023-11-04 15:29:10 25 4
gpt4 key购买 nike

int main() {
unsigned int i = 1;
typeof(-i) j = -i;
}

当我在 gdb 中查看 j 的类型时,它显示它是 unsigned int 类型。为什么类型没有移动到相应的签名类型?选择这种行为背后有什么原因吗?我发现该类型是否会更直观地转换为相应的带符号类型。

最佳答案

一元否定运算符 - 不会改变其参数的类型,除了应用整数提升。 C standard 的第 6.5.3.3p3 节状态:

The result of the unary - operator is the negative of its (promoted) operand. The integer promotions are performed on the operand, and the result has the promoted type

整数提升的细节在6.3.1.1p2节有详细介绍:

The following may be used in an expression wherever an int or unsigned int may be used:

  • An object or expression with an integer type (other than int or unsigned int) whose integer conversion rank is less than or equal to the rank of int and unsigned int.
  • A bit-field of type _Bool, int, signed int, or unsigned int.

If an int can represent all values of the original type (as restricted by the width, for a bit-field), the value is converted to an int; otherwise, it is converted to an unsigned int. These are called the integer promotions. All other types are unchanged by the integer promotions.

i 的类型是 unsigned int,根据上面的段落,它不受整数提升的影响(实际上,它是整数提升的目标类型)。因此不执行任何提升,-i 的类型与 i 的类型相同。

关于c++ - 为什么(-i)的类型,其中i是unsigned int,还是unsigned int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59037962/

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