当 运行 一个无限循环时,为什么 int 或 char 在最后给出负值

When run an infintie loop why int or char gives negative value at the end

#include <stdio.h>

int main()
{
    signed char x = 0;
    for (; x >= 0; x++);
    printf("%d\n", x);
    return 0;
}

这段代码的输出是-128。谁能解释一下为什么?

实现定义的行为

signed char x = 0; for (; x >= 0; x++); 从 0 迭代 x 到 127 (SCHAR_MAX),到目前为止一切正常。

在下一次迭代中,x++ 表现得像 x = x + 1;,尝试将 128 分配给 signed char x。因为这超出了 signed char 范围:

Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.
(C spec relating to conversions to a signed type)

一个常见的实现定义的结果是环绕到 -128 或 SCHAR_MIN。可能会发生其他结果,例如分配最大值 127 导致无限循环。

没有符号整数溢出,只是赋值超出范围。


代码的可移植性不高,应该避免使用。

这是实现定义的行为。

在 x86 平台上,我所知道的所有编译器,当 x 是 127 并且你添加 1 它执行无符号加法,结果是 0b10000000,其二进制补码有符号整数格式是 -128

由于 x-128 循环终止并打印出 -128