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

  • [[noreturn]] — function never returns
  • [[carries_dependency]] — memory-order dependency hint (removed in C++26)
  • [[deprecated]]
  • [[deprecated("reason")]]
  • [[fallthrough]] — intentional switch fallthrough
  • [[maybe_unused]] — suppress unused warnings
  • [[nodiscard]] — warn if return value ignored
  • [[nodiscard("reason")]]
  • [[likely]] — branch prediction hint
  • [[unlikely]] — branch prediction hint
  • [[no_unique_address]] — allow overlapping member storage
  • [[assume(expression)]] — compiler may assume expression is true
  • [[indeterminate]] — object has indeterminate value
  • 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:

    Clang Attribute Reference

    Warnings About Attributes

    Attributes are hints, not guarantees.

    Key takeaways