[英]Don't understand the output of program with a switch block
我想了解此代碼的 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;
}
如果沒有 break 語句,一個 case 結尾的代碼將落入下一個 case 的代碼中。
因此,當x
達到值 6.1 時,由於x*x
仍然小於 50,因此您點擊case 6
,並且沒有 break 語句,您還輸入了case 5
和case 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= %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: ^~~~
如果您的代碼有意進入下一個案例, gcc
將遵循注釋該意圖的注釋。 然后不會發出警告。
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.