解决warning: this statement may fall through [-Wimplicit-fallthrough=]

使用switch如果缺少break,gcc编译的时候会报相关的warnning信息,如果是忘记写,这样肯定是有问题的,警告信息可以帮助我们排除隐藏的bug。要消除警告很简单,把break加上就行。

但是有时候,我们的需求就是需要继续向下执行,是故意为之,那么这种warnning应该怎么消除呢?我们需要告诉编译器我们是故意这样写的,让它忽略该问题。

#ifndef __has_cpp_attribute
#define __has_cpp_attribute(x) 0
#endif

#ifndef __has_c_attribute
#define __has_c_attribute(x) 0
#endif

#ifndef __has_attribute
#define __has_attribute(x) 0
#endif
 
#if __has_cpp_attribute(fallthrough) || __has_c_attribute(fallthrough)
#define FALLTHROUGH [[fallthrough]]
#elif __has_attribute(fallthrough)
#define FALLTHROUGH __attribute__((fallthrough))
// Note, there could be more branches here, like using `[[gsl::suppress]]` for MSVC
#else
#define FALLTHROUGH
#endif

// example 
void example(int cond) { 
  switch (cond) { 
  case 0:
    dosomething(); 
    FALLTHROUGH;  
  case 1:
    myfun();
    break;
  default: 
    break;
  }
}

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 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值