我正在终端中运行此c程序
#include <stdio.h>
int main() {
int result = 0;
while(result <= 0)
{
int result = (getchar() != EOF);
result = 2;
printf("x");
}
printf("out\n");
}
此后,我输入单词“ hello”,然后返回。结果是我得到多个“ x”字符。
为什么这在第一个“ x”之后不终止?
答案 0 :(得分:5)
您正在while循环中重新声明(阴影result
)。 result
中使用的while(result <= 0)
是在循环外部声明的那个。
答案 1 :(得分:0)
好吧
#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");
}
从注释中可以推断出,在result
测试中比较的while
变量是外部变量,而内部变量隐藏了外部变量,因此无法对其进行赋值在循环主体中,因此循环将永远运行。您将获得x
上打印的stdout
的无限字符串。