C - 棘手的开关盒工作..! [英] C - Tricky Switch Case working .. !
问题描述
各位,
最近开始学习 C.
卡在一个点上.它是关于 switch-case 语句的工作.
Recently started learning C.
Stuck at a point. Its about working of switch-case statement.
代码如下:
#include<stdio.h>
int main() {
int i=4;
switch(i) {
default :
printf("%s","Default");
case 0:
printf("%s","Case 0");
case 1:
printf("%s","Case 1");
case 2:
printf("%s","Case 2");
return 0;
}
}
我个人认为,应该打印Default
",因为它与任何大小写值都不匹配.
但是当我在 Turbo C 中运行代码时,我观察到的是:
I personally think, "Default
" should be printed, as it doesn't match with any of case value.
But when I run the code in Turbo C, what I observed was this :
Default
Case 0
Case 1
Case 2
这里也观察到了同样的情况:http://www.ideone.com/pFh1d
Even same was observed here : http://www.ideone.com/pFh1d
有什么问题?这是编译器问题还是我的代码中的任何错误?
What is the problem ? It is the compiler problem or any mistake in my code ?
PS:如果我必须首先编写默认情况,这有什么错.有什么危害吗?
但是一旦编译器知道它必须执行default语句,为什么还要在default case语句之后放一个break语句呢?
推荐答案
switch 语句将跳转到相应的 case
或 default
然后代码将继续直到下一个 break
语句.
The switch statement will jump to the appropriate case
or default
and then the code will continue until the next break
statement.
由于您的代码没有 break
,它将从 default:
开始,然后继续执行以下所有语句.在编写类似条件时,这有时是一个有用的技巧,但通常缺少 break 语句会导致混淆.
As your code has no break
it will start off at the default:
and simply continue through all the following statements. This can sometimes be a useful trick when programming similar conditions, but generally the lack of break statements will cause confusion.
还有最后的 return
在 switch 语句之后的错误位置.
Also the final return
is in the wrong place it should be after the switch statement.
修改如下.
int i=4;
switch(i) {
default :
printf("%s","Default");
break;
case 0:
printf("%s","Case 0");
break;
case 1:
printf("%s","Case 1");
break;
case 2:
printf("%s","Case 2");
break;
}
return 0;
这篇关于C - 棘手的开关盒工作..!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!