C 属性: maybe_unused (自 C23 起)
来自 cppreference.cn
< c | language | attributes
抑制未使用实体的警告。
目录 |
[edit] 语法
[[ maybe_unused ]] [[ __maybe_unused__ ]] |
|||||||||
[edit] 解释
此属性可以出现在以下实体的声明中
- struct/union: struct [[maybe_unused]] S;,
- typedef 名称: [[maybe_unused]] typedef S* PS;,
- 对象: [[maybe_unused]] int x;,
- 结构体/联合体成员: union U { [[maybe_unused]] int n; };,
- 函数: [[maybe_unused]] void f(void);,
- 枚举: enum [[maybe_unused]] E {};,
- 枚举器: enum { A [[maybe_unused]], B [[maybe_unused]] = 42 };.
如果编译器对未使用实体发出警告,则对于任何声明为 maybe_unused
的实体,该警告将被抑制。
[edit] 示例
运行此代码
#include <assert.h> [[maybe_unused]] void f([[maybe_unused]] _Bool cond1, [[maybe_unused]] _Bool cond2) { [[maybe_unused]] _Bool b = cond1 && cond2; assert(b); // in release mode, assert is compiled out, and b is unused // no warning because it is declared [[maybe_unused]] } // parameters cond1 and cond2 are not used, no warning int main(void) { f(1, 1); }
[edit] 参见
C++ 文档 中关于 maybe_unused 的部分
|