C++17 关键字fallthrough

在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;
  

int main()
{
    int n = 1;

    // Switch Cases
    switch (n) {
		case 1: {
			cout << "enter one \n";
		}
		case 2: {
			cout << "enter two \n";
		}
		case 3: {
			cout << "enter three \n";
		}
		default: {
			cout << "enter default \n";
		}
    }

    return 0;
}

所以输出为

enter one 
enter two 
enter three 
enter 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 << "enter 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 << "enter 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 << "enter three \n";
      |                 ^~~~~~~~~~~~~~~~~~~~~~~
1.cpp:25:5: note: here
   25 |     default: {
      |     ^~~~~~~

但是有些时候我们为了实现一些特定的逻辑,所以有意不加break, 但是又不想听到编译器的抱怨,该怎么样让编译器"闭嘴"呢?此时C++17中引入的fallthrough便派上用场了

#include <iostream>
using namespace std;
  
int main()
{
    int n = 1;

    // Switch Cases
		switch (n) {
		case 1: {
			cout << "enter one \n";
			[[fallthrough]];
		}
		case 2: {
			cout << "enter two \n";
			[[fallthrough]];
		}
		case 3: {
			cout << "enter three \n";
			[[fallthrough]];
		}
		default: {
			cout << "enter default \n";
		}
    }
    return 0;
}

编译结果如下,编译器真的"闭嘴"了

> g++-9 -W 1.cpp

  • 6
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

私房菜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值