[英]Don't understand the output of program with a switch block
I want to understand the output of this code, specifically the 2 last lines of the output (lines 4 and 5).我想了解此代码的 output,特别是 output 的最后两行(第 4 行和第 5 行)。
#include <stdio.h>
#include <stdlib.h>
int main()
{
double x = 2.1;
while (x * x <= 50) {
switch ((int) x) {
case 6:
x--;
printf("case 6, x= %f\n ", x);
case 5:
printf("case 5, x=%f\n ", x);
case 4:
printf("case 4, x=%f\n ", x);
break;
default:
printf("something else, x=%f\n ", x);
}
x +=2;
}
return 0;
}
Without a break statement, the code at the end of one case will fall through into the code of the next case.如果没有 break 语句,一个 case 结尾的代码将落入下一个 case 的代码中。
So, when x
reaches the value 6.1, since x*x
is still less than 50, you hit case 6
, and with no break statement, you also enter the case 5
and case 4
code.因此,当
x
达到值 6.1 时,由于x*x
仍然小于 50,因此您点击case 6
,并且没有 break 语句,您还输入了case 5
和case 4
代码。 So, the value 5.1 (the result of decrementing x
) is printed 3 times.因此,值 5.1(递减
x
的结果)被打印 3 次。
This is a good opportunity to stress that you should compile your code with all warnings enabled.这是一个很好的机会来强调您应该在启用所有警告的情况下编译您的代码。 With
gcc -W -Wall
, your program will generate the following warnings:使用
gcc -W -Wall
,您的程序将生成以下警告:
.code.tio.c: In function 'main': .code.tio.c:12:17: warning: this statement may fall through [-Wimplicit-fallthrough=] printf("case 6, x= %f\n ", x); ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~.code.tio.c:14:13: note: here case 5: ^~~~.code.tio.c:15:17: warning: this statement may fall through [-Wimplicit-fallthrough=] printf("case 5, x=%f\n ", x); ^~~~~~~~~~~~~~~~~~~~~~~~~~~~.code.tio.c:17:13: note: here case 4: ^~~~
If your code is intentionally wanting to fall-through to the next case, gcc
will honor a comment annotating that intent.如果您的代码有意进入下一个案例,
gcc
将遵循注释该意图的注释。 The warning will then not be emitted.然后不会发出警告。
switch ((int) x) {
case 6:
x--;
printf("case 6, x= %f\n ", x);
// FALLTHROUGH
case 5:
printf("case 5, x=%f\n ", x);
// FALLTHROUGH
case 4:
printf("case 4, x=%f\n ", x);
break;
default:
printf("something else, x=%f\n ", x);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.