为什么 (unsigned int) 在 C 中的输出中产生负数

why (unsigned int) produces negative numbers in the output in C

我发现在下面的代码中输出总是带有负号,尽管我在初始化语句中指出变量 x 的位是无符号整数。

为什么 ~x 会产生一个负符号数,而没有分配给数字符号的位首先反映出来?

#include <stdio.h>
void main() {
    unsigned int x = 11;
    printf("not x=%d", ~x);
}

此行为取决于平台,但基本答案是 printf 不知道您传递的内容已声明为未签名。这只是一个值。如果您使用 %d 格式,该值将被解释为带符号的整数。如果您使用 %u,它将被解释为无符号。在使用二进制补码表示的处理器上,设置了最高有效位的值是负数。由于 ~11 设置了该位,因此显示为负数。

是关于printf对你传递的参数的解释。

unsigned int x = 11;
printf("not x=%d", ~x);

在函数调用期间,默认参数 promotions 会将 ~x 作为 unsigned int 类型传递给 printf。由于来自 printf.

签名的 va_args,默认参数提升被应用

此外,整数提升 用于计算 ~x -- 来自 6.5.3.3 Unary arithmetic operators:

The result of the ~ operator is the bitwise complement of its (promoted) operand (that is, each bit in the result is set if and only if the corresponding bit in the converted operand is not set). The integer promotions are performed on the operand, and the result has the promoted type. If the promoted type is an unsigned type, the expression ~E is equivalent to the maximum value representable in that type minus E.

因此您传递了一个无符号整数,但是 printf 会将其转换为 int,因为 %d 期望找到一个 int。