C++ attribute: maybe_unused (since C++17)

From cppreference.com
< cpp‎ | language‎ | attributes
 
 
C++ language
General topics
Flow control
Conditional execution statements
if
Iteration statements (loops)
for
range-for (C++11)
Jump statements
Functions
Function declaration
Lambda function expression
inline specifier
Dynamic exception specifications (until C++17*)
noexcept specifier (C++11)
Exceptions
Namespaces
Types
Specifiers
decltype (C++11)
auto (C++11)
alignas (C++11)
Storage duration specifiers
Initialization
Expressions
Alternative representations
Literals
Boolean - Integer - Floating-point
Character - String - nullptr (C++11)
User-defined (C++11)
Utilities
Attributes (C++11)
Types
typedef declaration
Type alias declaration (C++11)
Casts
Implicit conversions - Explicit conversions
static_cast - dynamic_cast
const_cast - reinterpret_cast
Memory allocation
Classes
Class-specific function properties
explicit (C++11)
static
Special member functions
Templates
Miscellaneous
 
 
Attributes
(C++14)
(C++17)
maybe_unused
(C++17)
(C++20)(C++20)
(C++23)
 

Suppresses warnings on unused entities.

Syntax

[[maybe_unused]]

Explanation

This attribute can appear in the declaration of the following entities:

For entities declared [[maybe_unused]], if the entities or their structured bindings are unused, the warning on unused entities issued by the compiler is suppressed.

Example

#include <cassert>
 
[[maybe_unused]] void f([[maybe_unused]] bool thing1,
                        [[maybe_unused]] bool thing2)
{
    [[maybe_unused]] bool b = thing1 && thing2;
    assert(b); // in release mode, assert is compiled out, and b is unused
               // no warning because it is declared [[maybe_unused]]
} // parameters thing1 and thing2 are not used, no warning
 
int main() {}

Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
CWG 2360 C++17 could not apply [[maybe_unused]] to structured bindings allowed

See also