while 循环中 getchar() 的行为

Behaviour of getchar() in a while loop

我是运行终端里的这个c程序

#include <stdio.h>

int main() {
    int result = 0;

    while(result <= 0) 
    {
        int result = (getchar() != EOF);
        result = 2;
        printf("x");        
    }

    printf("out\n");
}

之后,我输入 "hello" 之后是 return。结果是我得到多个 'x' 个字符。

为什么这在第一个 'x' 之后没有终止?

您正在 while 循环内重新声明(隐藏 result)。 while(result <= 0) 中使用的 result 是在循环外声明的

嗯,

#include <stdio.h>

int main() {
    int result = 0;  /* here *OUTER* result gets the value 0 */

    while(result <= 0) /* THIS MAKES THE While to execute forever */
    {
        int result = (getchar() != EOF);  /* THIS VARIABLE IS ***NOT*** THE outside result variable */
        result = 2; /* external block result is not visible here so this assign goes to the above inner result */
        printf("x");        
        /* INNER result CEASES TO EXIST HERE */
    }

    printf("out\n");
}

从注释中可以推导出,while测试中比较的result变量是外层的,而内层隐藏了外层,不能赋值在循环体中加入它,所以循环永远运行下去。 stdout.

上打印了一个无限长的 x 字符串