为什么下面的C代码会进入死循环?

问题描述 投票:0回答:1
#include <stdio.h>

int main() {
for (char c=0; c<128; c++) {
    printf("%c", c);
    }
}

代码的输出会一遍又一遍地打印整个字符列表。

但我也尝试运行此代码:

#include <stdio.h>

int main() {
    for (char c=0; c<127; c++) }
        printf("%c", c);
    }
}

唯一的变化是条件。现在它运行良好,不会进入无限循环。
这是什么原因呢?

c for-loop ascii
1个回答
0
投票

在 C 中,char 结构只能保存 -127 到 127 之间的值(包括 -127 和 127)。你的 for 循环尝试去到 128,但是因为 char 只能容纳 127,所以它永远不会达到 128。

条件验证检查是否 c < 128, and stops when c == 128. When c = 127, the loop progresses making c + 1 = -127. So it loops again and again, and never stops because it never reaches 128.

第二个循环在 127 处停止,因为 char 结构最多可以容纳 127,因此条件满足,循环结束

© www.soinside.com 2019 - 2024. All rights reserved.