我只是想知道为什么这么多人最终在switch语句中使用continue
实际上根本不需要它,例如,循环中的嵌套switch语句。让我们说有人写了这个C代码
int get_option(){...}
main(){
int option;
while(1){
option = get_option();
switch(option){
case 0:
/* do something */
continue;
case 1:
/* do something */
break;
case 2:
/* do something */
continue;
default:
}
此处,结束continue
的案例似乎与break
的结果完全相同。在我看来,结束switch语句的正式方法是使用break
,因为无论如何,你总是可以使用它来结束语句是否嵌套在循环中。在这里使用continue
对我来说似乎很糟糕。
如果您能在切换声明中考虑我真正需要continue
的任何情况,请给我一个想法。
答案 0 :(得分:3)
它用于决定是否应该执行某些语句在之后的switch语句。这是一个例子:
#include <stdio.h>
#include <ctype.h>
int get_option(void)
{
int num;
do{
num = getchar();
} while(isspace(num));
if(isdigit(num))
return num - '0';
else
return -1;
}
int main(void)
{
int option;
while(1){
option = get_option();
switch(option){
case 0:
puts("You've entered 0");
continue; // <--- continue; gives you nothing
case 1:
puts("You've entered 1");
break; // <--- break; gives you "You've entered an odd number"
case 2:
puts("You've entered 2");
continue;
default:
puts("Input out of range!");
continue;
}
puts("You've entered an odd number"); // <--- Notice this line
}
}
输入和输出:
0
You've entered 0
1
You've entered 1
You've entered an odd number
2
You've entered 2
3
Input out of range!
答案 1 :(得分:1)
bool isPointOnShape (int, int);