![](/img/trans.png)
[英]How to fix this statement may fall through [-Werror=implicit-fallthrough=]?
[英]Why does gcc throw an implicit-fallthrough warning?
給定代碼:
#include <stdlib.h>
enum one {
A, B
};
enum two {
AA
};
int main(int argc, char *argv[])
{
enum one one = atoi(argv[1]);
enum two two = atoi(argv[2]);
if ((one != A && one != B) || two != AA)
return 1;
switch (one) {
case A:
switch (two) {
case AA:
return 2;
}
case B:
return 3;
}
return 0;
}
當我使用gcc -Wimplicit-fallthrough test_fallthrough.c
編譯它時,我收到以下警告
test_fallthrough.c: In function 'main':
test_fallthrough.c:21:3: warning: this statement may fall through [-Wimplicit-fallthrough=]
21 | switch (two) {
| ^~~~~~
test_fallthrough.c:25:2: note: here
25 | case B:
| ^~~~
它試圖警告什么,我能做些什么使它不發出警告(我寧願避免添加諸如/* Falls through. */
之類的評論)
通常,編譯器會在每個case
主體之后檢查break
語句,以確保程序流(失敗)沒有錯誤。
在您的情況下, case A
主體沒有break
,當switch
語句與case A
的語句匹配時,也讓case B
繼續執行。
switch (one) {
case A:
switch (two) {
case AA:
return 2;
}
// <------ no break here, flow will continue, or fall-through to next case body
case B:
return 3;
}
return 0;
}
您在第一個 switch 語句中缺少一個break
,它可能會落入第二種情況,它可以執行case A
,然后執行Case B
,因此會發出警告。
//...
switch (one)
{
case A:
switch (two)
{
case AA:
return 2;
}
break; //breaking case A removes the warning.
case B:
return 3;
}
//...
邊注:
argc
檢查argv[1]
和argv[2]
是否存在總是一個好主意。為什么 gcc 會引發隱式失敗警告?
好吧,因為它可能會失敗。
它試圖警告什么
當two != AA
時,從case A
到case B
的失敗。
我該怎么做才能不發出警告
在低於 7 的 gcc 上使用注釋,即。 禁用警告的標記之一:
/* falls through */
在 7 以上的 gcc 上,您可以使用屬性:
__attribute__((__fallthrough__));
在 10 以上的 gcc 上,您可以使用 C2x的屬性:
[[fallthrough]];
--
注意if (one != A || one != B || two != AA)
並沒有真正檢查任何東西,因為one != A || one != B
one != A || one != B
永遠為真。 我猜你打算這樣做if ((one != A && one != B) || two != AA)
。 無論如何, -Wimplicit-falthrough=
警告仍然if
考慮到這一點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.