解决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 

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
[warning] this statement may fall through [-wimplicit-fallthrough=] 的意思是“此语句可能会穿透”,是编译器给出的警告信息。它表示在 switch 语句中,某个 case 分支没有使用 break 或 return 等语句来结束,而是直接进入了下一个 case 分支,这可能会导致程序出现意外的行为。为了避免这种情况,可以在每个 case 分支的末尾加上 break 或 return 等语句来明确结束该分支。 ### 回答2: 最近在做C++开发的时候,经常会遇到一些编译器的警告,其中就有一个是“warning:this statement may fall through [-wimplicit-fallthrough=]”。 所谓的“fall through”,即是指 switch 语句中,同时满足多个 case 分支的情况,即程序在执行某个 case 时,会因为没有 break; 语句而继续执行下一个 case,这就是“fall through”,也称作“贯穿”。 在C++的编译器中,通常会设置一个警告选项“-Wimplicit-fallthrough”,用来提示开发者在 switch 语句中遗漏了 break; 而导致的“fall through”情况。可以使用“-Wno-implicit-fallthrough”宏取消此警告。 警告信息中的“this statement may fall through”是指,在当前的 switch 语句中,某个 case 分支中没有出现 break; 语句,因此有可能会发生“fall through”的情况。出现这种情况的时候,编译器会给出警告提示,开发者需要检查代码逻辑是否有误,并在需要的地方加入 break; 语句,以避免出现“fall through”的情况,从而保证程序的正确性。 此外,在代码审查的时候,也应该注意这个警告信息,及时发现和修复代码中的问题。避免出现不必要的“fall through”情况,能够增强代码的可读性和可维护性,也能够减少代码出错的概率,提高程序的质量和稳定性。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值