更多精彩内容,请关注微信公众号:后端技术小屋

在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

推荐阅读

更多精彩内容,请扫码关注微信公众号:后端技术小屋。如果觉得文章对你有帮助的话,请多多分享、转发、在看。
二维码