Namespaces
Variants

C attribute: maybe_unused (since C23)

From zh.cppreference.net

抑制未使用实体的警告。

目录

语法

[[ maybe_unused ]]
[[ __maybe_unused__ ]]

说明

此属性可出现在以下实体的声明中:

  • 结构体 / 联合体 : struct [ [ maybe_unused ] ] S ; ,
  • 类型定义名 : [ [ 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 的实体,该警告将被抑制。

示例

#include <assert.h>
[[maybe_unused]] void f([[maybe_unused]] _Bool cond1, [[maybe_unused]] _Bool cond2)
{
   [[maybe_unused]] _Bool b = cond1 && cond2;
   assert(b); // 在发布模式下,assert会被编译移除,此时b未被使用
              // 因其声明为[[maybe_unused]],不会产生警告
} // 参数cond1和cond2未被使用,但不会产生警告
int main(void)
{
    f(1, 1);
}

参见

C++ 文档 关于 maybe_unused