Ch3.13: attribute
What Attributes Are
Attributes provide additional information to the compiler. They do not change the meaning of the program, but they can enable warnings, optimizations, or special behavior.
Attributes use the syntax:
[[attribute]]
Attributes are part of the C++ language, not macros.
Basic Syntax
[[nodiscard]]
int compute();
You can apply attributes to functions, variables, types, and statements.
Multiple Attributes
You can list multiple attributes inside the same pair of brackets:
[[nodiscard, maybe_unused]]
int f();
Or write them separately:
[[nodiscard]]
[[maybe_unused]]
int f();
Both forms are equivalent.
Attribute Namespaces
Standard attributes use the std namespace implicitly:
[[nodiscard]]
[[maybe_unused]]
[[deprecated]]
Vendor-specific attributes use explicit namespaces:
[[gnu::always_inline]]
[[clang::fallthrough]]
[[msvc::noinline]]
Namespaces prevent collisions between different compilers.
Using Attribute Syntax
C++ also supports a using-attribute syntax that applies a namespace to multiple attributes at once.
[[using CC: opt(1), debug]]
void f();
This is equivalent to:
[[CC::opt(1), CC::debug]]
void f();
Standard C++ Attributes (C++11 → C++26)
The C++ standard defines a growing set of attributes. Below is a summary of the most important ones. For full details, see:
cppreference.com: C++ attributes
C++11
Attributes on Statements
Some attributes apply directly to statements. The most common are
[[likely]] and [[unlikely]].
The correct syntax places the attribute after the condition and before the statement body:
if (x > 0) [[likely]] {
print("positive\n");
} else [[unlikely]] {
print("non-positive\n");
}
The attribute applies to the statement, not the condition.
Clang Attributes
Clang supports a very large set of additional attributes for diagnostics, optimization, ABI control, code generation, and more.
Examples:
[[clang::always_inline]]
[[clang::noinline]]
[[clang::reinitializes]]
[[clang::trivial_abi]]
Clang provides far more attributes than the C++ standard. Full list:
Warnings About Attributes
- Attributes do not change program semantics.
- Compilers may ignore attributes they do not recognize.
- Attributes should not be used to hide logic errors.
- Vendor attributes reduce portability.
Attributes are hints, not guarantees.
Key takeaways
- Attributes provide hints: they do not change program meaning.
- Standard syntax:
[[attribute]]. - Multiple attributes:
[[a, b]]or stacked blocks. - Namespaces:
gnu::,clang::,msvc::. - Using-attribute syntax:
[[using CC: opt(1), debug]]. - Statement attributes:
if (cond) [[likely]] { ... }. - Standard attributes: list included.
- Clang provides many more attributes: see Clang docs.