问题
嵌套中的continue会使程序跳到哪里呢?我翻了一下《C Primer Plus》第7章并从中了解到:嵌套中的continue仅仅影响“包含它的最里层的结构”。这里我利用第8章中的一段代码来印证这一特性。
代码如下
//guess.c -- 一个低效且错误的猜数程序
#include <stdio.h>
int main(void)
{
int guess = 1;
printf("Pick an integer from 1 to 100. I will try to ");
printf("guess it .\nRespond with a y if my guess is ");
printf("right and with\nan n if it is wrong.\n");
printf("Uh...is your number %d?\n", guess);
while (getchar() != 'y'){
printf("well,then,is it %d?\n", ++guess);
while (getchar () != '\n')
continue;
}
printf("I knew I could do it!\n");
return 0;
}
运行结果如下
Pick an integer from 1 to 100. I will try to guess it .
Respond with a y if my guess is right and with
an n if it is wrong.
Uh...is your number 1?
n
well,then,is it 2?
no
well,then,is it 3?
no sir
well,then,is it 4?
yes
I knew I could do it!
总结
不管是输入n,no还是no sir,n后面剩余的部分(包括\n)都会被 while (getchar () != '\n')
以及后面的continue给吃掉,这说明嵌套中的continue仅仅影响“包含它的最里层的结构”。