- fallthrough
- 原因
- 实例代码
- 解决方法;
就是掉落穿透,比如从楼上掉下来一个导弹,直接就fall through 整个楼层。
原因这个是大家经过多年经验总结而来的一个警告,以防止疏忽大意导致代码里出现非程序员本意的代码逻辑来,缺少了break语句。逻辑,就是如果是要break,就要加上语句break;但是如果不加break,代表fallthrough,这个fallthrough不是每个人都能意识到,或者是忘记了,所以要明确写上是否要fallthrough。
实例代码switch (cond)
{
case 1:
a = 1;
break;
case 2:
a = 2;/// 这一句的后面可能是少了break;如果在编译选项里加上Werror=implicit-fallthrough,给程序员一个提示。
case 3:
a = 3;
break;
}
如果是故意的,让代码fallthrough,就需要使用gcc提供的attribute:
attribute ((fallthrough)),
switch (cond)
{
case 1:
bar (0);
attribute ((fallthrough)); //在这里加上这个属性,就代表,我是故意这么做,不用报warning,错误。
default:
C++17 provides a standard way to suppress the ‘-Wimplicit-fallthrough’ warning using [[fallthrough]]; instead of the GNU attribute. In C++11 or C++14 users can use [[gnu::fallthrough]];, which is a GNU extension. Instead of the these attributes, it is also possible to add a fallthrough comment


![c: error: this statement may fall through [-Werror=implicit-fallthrough=] c: error: this statement may fall through [-Werror=implicit-fallthrough=]](http://www.mshxw.com/aiimages/31/935626.png)
