c语言 - 不理解带有开关块的程序输出



我想了解这段代码的输出,特别是输出的最后两行(第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= %fn ", x);
case 5:
printf("case 5, x=%fn ", x);
case 4:
printf("case 4, x=%fn ", x);
break;
default:
printf("something else, x=%fn ", x);
}
x +=2;
}
return 0;
}

如果没有break语句,一个案例结尾的代码将进入下一个案例的代码。

因此,当x达到值6.1时,由于x*x仍然小于50,因此您可以点击case 6,并且在没有break语句的情况下,您还可以输入case 5case 4代码。因此,值5.1(递减x的结果(被打印3次。

这是一个很好的机会来强调您应该在编译代码时启用所有警告。使用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= %fn ", 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=%fn ", x);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~
.code.tio.c:17:13: note: here
case 4:
^~~~

如果您的代码有意进入下一种情况,gcc将接受注释该意图的注释。然后将不会发出警告。

switch ((int) x) {
case 6:
x--;
printf("case 6, x= %fn ", x);
// FALLTHROUGH
case 5:
printf("case 5, x=%fn ", x);
// FALLTHROUGH
case 4:
printf("case 4, x=%fn ", x);
break;
default:
printf("something else, x=%fn ", x);

最新更新