在C++17中引入了fallthrough
属性。该属性主要用于switch
语句中。在C++的switch语句中,如果当前case
分支中不加break
, 便会执行下一个case
分支的代码。
如下所示,由于n
的值为1,代码首先执行case 1
分支,然后又因为case 1
分支中没有加break
,所以接着执行case 2
分支、case 3分支
,一直到default
分支
#include <iostream> using namespace std; // Driver Code int main() { int n = 1; // Switch Cases switch (n) { case 1: { cout << "work through one \n"; } case 2: { cout << "work through two \n"; } case 3: { cout << "work through three \n"; } default: { cout << "work through default \n"; } } return 0; }
所以输出为
work through one work through two work through three work through default
而很多C++初学者容易犯这样的错误:在本应当在case
分支中加入break
的时候却忘了加了。于是编译器会针对这种情况输出Warning
信息,提醒程序员他可能忘了加break
了。
> g++-9 -W 1.cpp 1.cpp:14:17: warning: this statement may fall through [-Wimplicit-fallthrough=] 14 | cout << "work through one \n"; | ^~~~~~~~~~~~~~~~~~~~~ 1.cpp:17:5: note: here 17 | case 2: { | ^~~~ 1.cpp:18:17: warning: this statement may fall through [-Wimplicit-fallthrough=] 18 | cout << "work through two \n"; | ^~~~~~~~~~~~~~~~~~~~~ 1.cpp:21:5: note: here 21 | case 3: { | ^~~~ 1.cpp:22:17: warning: this statement may fall through [-Wimplicit-fallthrough=] 22 | cout << "work through three \n"; | ^~~~~~~~~~~~~~~~~~~~~~~ 1.cpp:25:5: note: here 25 | default: { | ^~~~~~~
但是有些时候我们为了实现一些特定的逻辑,所以有意不加break
, 但是又不想听到编译器的抱怨,该怎么样让编译器"闭嘴"呢?此时C++17中引入的fallthrough
便派上用场了
#include <iostream> using namespace std; // Driver Code int main() { int n = 1; // Switch Cases switch (n) { case 1: { cout << "work through one \n"; [[fallthrough]]; } case 2: { cout << "work through two \n"; [[fallthrough]]; } case 3: { cout << "work through three \n"; [[fallthrough]]; } default: { cout << "work through default \n"; } } return 0; }
编译结果如下,编译器真的"闭嘴"了
$ g++-9 -W 1.cpp