使用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