# Attributes

> Attributes annotate entities and statements with information the compiler may use. Unknown ones are ignored, standard ones in the wrong place are errors, and a few of them are promises that cause undefined behavior when broken.

- **Source:** C++ Atlas (https://cppatlas.com/topics/attributes)
- **Track:** Program structure
- **Estimated reading time:** 12 minutes
- **ISO C++ clauses:** [dcl.attr.grammar] (https://eel.is/c++draft/dcl.attr.grammar), [dcl.attr.nodiscard] (https://eel.is/c++draft/dcl.attr.nodiscard), [dcl.attr.unused] (https://eel.is/c++draft/dcl.attr.unused), [dcl.attr.deprecated] (https://eel.is/c++draft/dcl.attr.deprecated), [dcl.attr.fallthrough] (https://eel.is/c++draft/dcl.attr.fallthrough), [dcl.attr.likelihood] (https://eel.is/c++draft/dcl.attr.likelihood), [dcl.attr.noreturn] (https://eel.is/c++draft/dcl.attr.noreturn), [dcl.attr.nouniqueaddr] (https://eel.is/c++draft/dcl.attr.nouniqueaddr), [dcl.attr.assume] (https://eel.is/c++draft/dcl.attr.assume), [intro.object] (https://eel.is/c++draft/intro.object)
- **cppreference links:** [Attribute specifier sequence](https://en.cppreference.com/w/cpp/language/attributes), [C++ attribute: nodiscard](https://en.cppreference.com/w/cpp/language/attributes/nodiscard), [C++ attribute: noreturn](https://en.cppreference.com/w/cpp/language/attributes/noreturn), [C++ attribute: assume](https://en.cppreference.com/w/cpp/language/attributes/assume), [C++ attribute: no_unique_address](https://en.cppreference.com/w/cpp/language/attributes/no_unique_address), [C++ attribute: fallthrough](https://en.cppreference.com/w/cpp/language/attributes/fallthrough), [C++ attribute: likely, unlikely](https://en.cppreference.com/w/cpp/language/attributes/likely), [C++ attribute: indeterminate](https://en.cppreference.com/w/cpp/language/attributes/indeterminate)
- **Prerequisites:** object-layout-and-alignment, strict-aliasing-and-undefined-behavior

## The one idea

An attribute is a note attached to a declaration, a type or a statement, written in double square brackets. The language promises very little about what any note does. Unknown attributes are ignored, and most standard ones only *encourage* a warning or an optimization.

That makes it easy to forget the exceptions. A few standard attributes are claims you make to the compiler, and the optimizer is entitled to believe them. A `[[noreturn]]` function that returns, or an `[[assume]]` whose expression is false, is undefined behavior. `[[no_unique_address]]` changes the layout of a class.

> **Mental model.** Read every attribute as one of three things: a request for a diagnostic (`nodiscard`, `deprecated`, `maybe_unused`, `fallthrough`), an optimization hint that cannot change meaning (`likely`, `unlikely`), or a promise the program must keep (`noreturn`, `assume`, `indeterminate`). Only the third kind can turn a correct-looking program into undefined behavior. `no_unique_address` is the odd one out: it permits a layout change.

## Syntax and appertainment

An attribute specifier is `[[ ... ]]` holding a comma-separated list. Each attribute is an optionally namespaced name, optionally followed by a parenthesized argument list made of balanced tokens: `[[nodiscard]]`, `[[deprecated("use g")]]`, `[[gnu::always_inline]]`. Since C++17 `[[using gnu: always_inline, hot]]` applies a namespace to every name in the list, and the names inside may then not be namespaced themselves.

Where you write it decides what it *appertains* to:

| Position | Appertains to |
| --- | --- |
| start of a declaration: `[[nodiscard]] int f();` | each entity declared |
| after the declarator-id: `int x [[maybe_unused]];` | that one entity |
| after `class`, `struct`, `union` or `enum`: `struct [[nodiscard]] S` | the class or enumeration |
| after the type specifiers: `int [[vendor::x]] y;` | the type |
| start of a statement: `[[likely]] return 0;` | the statement |
| start of a label: `[[unlikely]] case 3:` | the label |

The table hides a common mistake. An attribute at the start of a declaration appertains to the entities its declarators declare. A class definition with no declarator declares no such entity, so the grammar does not allow the attribute there at all.

```cpp
struct [[nodiscard]] Error { int code; };   // OK: Error is a nodiscard type
// [[nodiscard]] struct Bad { int code; };  // ill-formed; GCC ignores it with a warning,
//                                           // Clang rejects it
```

Lambdas follow the same logic. Before C++23 there was no place to put an attribute that appertains to a lambda's function call operator; C++23 allows one right after the capture list.

```cpp
auto make = [] [[nodiscard]] () { return 42; };   // C++23: appertains to operator()

void demo() {
  make();   // warning: discarded nodiscard result
}
```

One attribute specifier does not use brackets at all. `alignas` is grammatically an attribute specifier too, which is why it can appear in the same positions, but its rules live with alignment rather than here.

## Unknown and misplaced attributes

[dcl.attr.grammar] says an attribute token the implementation does not recognize is ignored. This is what makes vendor attributes portable: GCC ignores `[[msvc::no_unique_address]]`, MSVC ignores `[[gnu::cold]]`, and both compile. Before C++17, the effect of an unrecognized attribute was implementation-defined. Compilers still warn, with `-Wattributes` in GCC and `-Wunknown-attributes` in Clang, and the argument tokens must still be balanced.

Standard attributes get no such latitude. If a standard attribute appears where it may not apply, the program is ill-formed. `[[noreturn]]` on a variable, `[[fallthrough]]` not followed by a case label, and `[[likely, unlikely]]` together are all errors in the standard's eyes, even where GCC only warns.

```cpp
[[acme::fast]] int f();      // ignored: unknown attribute
[[noreturn]] int v;          // ill-formed: noreturn applies only to functions
```

To ask whether an attribute is supported, use `__has_cpp_attribute(name)` inside `#if`. It yields 0 for an unknown attribute and otherwise a date, such as `201907L` for `nodiscard` with a reason string.

## Attributes that ask for a diagnostic

`[[nodiscard]]` (C++17) on a function, or on a class or enumeration type returned by value, asks for a warning when a call's result is discarded. C++20 added a reason string and allowed it on constructors, so `S(1);` as a statement can warn too. A cast to `void` is the sanctioned way to discard.

The type form only covers calls that return the type by value. A function returning a reference to a nodiscard type does not trigger it, because its return type is a reference, not the class.

```cpp
struct [[nodiscard]] Error { int code; };
Error make();
Error& last();

void demo() {
  make();          // warning: discarded nodiscard type
  last();          // no warning: the return type is Error&
  (void)make();    // no warning: explicitly discarded
}
```

> **Standardese.** The standard never makes ignoring a nodiscard result ill-formed. [dcl.attr.nodiscard] puts the warning under "recommended practice", so a conforming compiler may stay silent.

`[[maybe_unused]]` (C++17) suppresses unused warnings for variables, parameters, functions, types, enumerators and structured bindings. `[[deprecated]]` (C++14), optionally with a message, marks a name whose use should warn; it also works on namespaces, enumerators and template specializations.

`[[fallthrough]];` (C++17) is a null statement that documents an intentional fall from one case into the next. The rule is strict: the next statement executed after it must be a statement labelled with a `case` or `default` of the same `switch`. Placing it at the end of the last case is ill-formed.

## Hints that change no meaning

`[[likely]]` and `[[unlikely]]` (C++20) go on a statement or label and say a path is more or less probable. They affect only code layout and branch prediction hints. A path containing a likely label is presumed more probable than one without, and compilers are free to ignore all of it. The two cannot appear on the same statement.

```cpp
int classify(int x) {
  switch (x) {
    [[likely]] case 0: return 1;
    [[unlikely]] case 1: return 2;
    default: return 3;
  }
}
```

`[[no_unique_address]]` (C++20) is not a pure hint, because it lets a non-static data member overlap others, which normally changes `sizeof`. It is still optional: MSVC ignores it for ABI reasons and spells it `[[msvc::no_unique_address]]`. What the standard does guarantee is that two distinct objects of the same type never share an address, even with the attribute.

```cpp
struct Empty {};
struct Pair {
  [[no_unique_address]] Empty a;
  [[no_unique_address]] Empty b;   // same type as a: &p.a != &p.b is guaranteed
  int i;
};
```

## Promises the optimizer believes

`[[noreturn]]` (C++11) says a function never returns to its caller. It may throw, loop forever or end the program, but if control ever returns, the behavior is undefined. The compiler uses the promise to delete code after the call and to silence missing-return warnings. The standard library declares `std::exit`, `std::abort`, `std::terminate` and `std::rethrow_exception` this way, among others. The first declaration of the function must carry the attribute if any declaration does. Within one file that is diagnosed; across files it is ill-formed with no diagnostic required.

```cpp
[[noreturn]] void fail(const char* why);

int parse(int x) {
  if (x < 0) fail("negative");   // compiler may assume this never comes back
  return x;
}
```

`[[assume(expr)]];` (C++23) is a statement that tells the compiler `expr` would be true at that point. The expression is never evaluated, so side effects in it never happen. If it would not evaluate to true, the behavior is undefined. The point is to give the optimizer facts it cannot prove, such as a divisor being positive or a size being a multiple of four, so that it can drop the code for the cases you have ruled out.

```cpp
#include <cstdio>
int main() {
  int i = 0;
  [[assume(++i > 0)]];       // not evaluated: i stays 0
  std::printf("%d\n", i);    // prints 0
}
```

> **Pitfall.** `assert(cond)` checks in debug builds and does nothing under `NDEBUG`. `[[assume(cond)]]` never checks and lets the optimizer delete code that handles the case where `cond` is false. Turning asserts into assumptions for release builds turns every failing assert into undefined behavior.

`[[indeterminate]]` is C++26. C++26 makes reading an uninitialized automatic variable *erroneous behavior*: the variable holds an implementation-chosen value, and reading it is a bug the implementation may diagnose, or even stop the program for, but may not treat as undefined. `[[indeterminate]]` on such a variable, or on a function parameter, opts back into the old rules: the value is indeterminate and reading it is undefined behavior. It exists for performance-critical buffers that are always written before they are read. GCC 16 accepts it with `-std=c++26`; Clang 21 ignores it as unknown. The erroneous behavior rules themselves belong to the C++26 language-changes topic.

## What to remember

- Position decides appertainment; put class attributes after the class key, as in `struct [[nodiscard]] S`.
- Unknown attributes are ignored since C++17; misplaced standard attributes are ill-formed.
- `[[using ns: a, b]]` namespaces a whole list, and the names inside cannot repeat a namespace.
- `nodiscard`, `deprecated`, `maybe_unused` and `fallthrough` only request diagnostics; none makes discarding a result ill-formed.
- `nodiscard` on a type covers by-value returns only.
- `[[fallthrough]];` must be followed by a case or default label of the same switch.
- `likely` and `unlikely` are pure hints; `no_unique_address` may change layout but never merges two objects of one type.
- A `noreturn` function that returns, or an `assume` that is false, is undefined behavior.
- An `assume` expression is never evaluated.
- `[[indeterminate]]` (C++26) opts an uninitialized variable out of erroneous behavior and back into undefined behavior.

## Concept Map Outline

- **Attributes:** Annotations on entities and statements: diagnostic requests, hints, and promises the optimizer may exploit.
  - **Syntax and placement:** Double brackets; the position decides what an attribute appertains to.
    - **Arguments:** An attribute may take a parenthesized list of balanced tokens, as in deprecated("use g").
    - **using prefix (C++17):** [[using gnu: hot, cold]] namespaces a list; the names inside cannot be namespaced again.
    - **Class attributes:** Write struct [[nodiscard]] S; an attribute before struct with no declarator is ill-formed.
    - **Statements and labels:** likely, unlikely and fallthrough attach to statements or labels, not declarations.
  - **Unknown vs misplaced:** Unrecognized attributes are ignored; standard ones used wrongly are errors.
    - **Ignored (C++17):** An unrecognized attribute token is ignored; in C++11 and C++14 this was implementation-defined.
    - **Misplaced standard:** A standard attribute applied where it cannot apply makes the program ill-formed.
    - **__has_cpp_attribute:** Yields 0 if unsupported, otherwise a date such as 201907L for nodiscard.
  - **Diagnostic requests:** They encourage warnings and never make code ill-formed by being violated.
    - **nodiscard:** C++17; reason string and constructors in C++20; type form covers by-value returns only.
    - **deprecated:** C++14; optional message; works on namespaces, enumerators and specializations.
    - **maybe_unused:** C++17; silences unused warnings for variables, functions, types and bindings.
    - **fallthrough:** C++17 null statement; the next statement must carry a case or default label.
  - **Hints and layout:** Optimization information that compilers may ignore.
    - **likely, unlikely:** C++20 path probability hints; both on one statement is ill-formed.
    - **no_unique_address:** C++20; lets a member overlap others, changing sizeof; MSVC ignores it.
    - **Same-type rule:** Two distinct objects of the same type never share an address.
  - **Promises:** Breaking these is undefined behavior, and the optimizer relies on them.
    - **noreturn:** C++11; returning is UB; the first declaration must carry it if any does.
    - **assume (C++23):** The expression is not evaluated; if it would be false, behavior is undefined.
    - **assume vs assert:** assert checks in debug builds; assume never checks and lets code be deleted.
    - **indeterminate (C++26):** Opts an uninitialized variable out of erroneous behavior back into UB on read.

## Standardese Quiz Questions

### Question 1 [warmup] ([dcl.attr.nodiscard])

In C++23, what does the standard require of a compiler translating `demo`?

```cpp
[[nodiscard]] int compute();

void demo() {
  compute();
}
```

A. It must reject the program: discarding the result is ill-formed
B. It must issue a diagnostic, but may still accept the program
C. Nothing: a warning is only recommended practice
D. Nothing, but calling `demo` is undefined behavior

**Answer (C):** Nothing: a warning is only recommended practice

**Why:** [dcl.attr.nodiscard] only encourages a warning when a nodiscard call's result is discarded; it appears under recommended practice. The program is well-formed, a silent compiler is conforming, and nothing about the call's behavior changes. GCC and Clang do warn, which is why the first two options feel right.

### Question 2 [warmup] ([dcl.attr.grammar])

In C++23, is this program well-formed? No compiler you know of supports `acme::fast`.

```cpp
[[acme::fast]] int f();

int f() { return 1; }

int main() { return f(); }
```

A. Ill-formed: `acme::fast` is not a recognized attribute
B. Well-formed: an unrecognized attribute is ignored
C. Implementation-defined behavior
D. Ill-formed: attribute namespaces other than `gnu`, `clang` and `msvc` are reserved

**Answer (B):** Well-formed: an unrecognized attribute is ignored

**Why:** Since C++17, [dcl.attr.grammar] says an attribute token the implementation does not recognize is ignored, which is what lets vendor attributes appear in portable code. Compilers usually warn, as GCC does with `-Wattributes`. Implementation-defined behavior was the C++11 and C++14 rule for attributes not specified by the standard.

### Question 3 [warmup] ([dcl.attr.assume])

In C++23, what does this program print?

```cpp
#include <cstdio>

int main() {
  int i = 0;
  [[assume(++i > 0)]];
  std::printf("%d\n", i);
}
```

A. `1`
B. Undefined behavior
C. Nothing: an assumption may not have side effects, so it is ill-formed
D. `0`

**Answer (D):** `0`

**Why:** The expression of an assumption is never evaluated, so `++i` never runs and `i` is still 0. There is no undefined behavior, because the expression would be true if it were evaluated. Side effects are allowed in the expression; they are simply discarded, and Clang warns that such an assumption is ignored.

### Question 4 [tricky] ([dcl.pre], [dcl.attr.grammar])

In C++23, what is the effect of this declaration?

```cpp
[[nodiscard]] struct Error { int code; };
```

A. `Error` becomes a nodiscard type, the same as `struct [[nodiscard]] Error`
B. The attribute is ignored because it is in an unrecognized position
C. It is ill-formed: an attribute at the start of a declaration needs a declarator to appertain to
D. The attribute applies to the next function declared

**Answer (C):** It is ill-formed: an attribute at the start of a declaration needs a declarator to appertain to

**Why:** An attribute specifier at the start of a simple declaration appertains to the entities its declarators declare, and the grammar only allows it when there is a declarator list. This declaration has none, so it is ill-formed; the class attribute belongs after the class key, as in `struct [[nodiscard]] Error`. Clang rejects it, while GCC only warns that the attribute is ignored, which makes the second option look right.

### Question 5 [tricky] ([dcl.attr.nodiscard])

Which of the discarded calls in `demo` are nodiscard calls, the ones compilers are encouraged to warn about?

```cpp
struct [[nodiscard]] Error { int code; };

Error make();
Error& last();

void demo() {
  make();
  last();
}
```

A. Both calls
B. Only `make()`
C. Only `last()`
D. Neither: the attribute is on the type, not on the functions

**Answer (B):** Only `make()`

**Why:** A nodiscard call is a call to a function declared nodiscard, or a call whose return type is a class or enumeration type marked nodiscard. `make` returns `Error` by value, so it qualifies. `last` returns `Error&`, a reference type, so the type's attribute does not apply; GCC warns about `make()` only.

### Question 6 [tricky] ([dcl.attr.fallthrough])

In C++23, is this function well-formed?

```cpp
int f(int x) {
  switch (x) {
    case 1:
      ++x;
      [[fallthrough]];
    case 2:
      return x;
    default:
      ++x;
      [[fallthrough]];
  }
  return x;
}
```

A. Well-formed: falling out of the switch is a kind of fall-through
B. Undefined behavior only when the default branch is taken
C. Well-formed, but compilers may warn
D. Ill-formed: the second `[[fallthrough]];` is not followed by a case or default label

**Answer (D):** Ill-formed: the second `[[fallthrough]];` is not followed by a case or default label

**Why:** [dcl.attr.fallthrough] requires the next statement executed after a fallthrough statement to be labelled with a case or default label of the same switch, and makes the program ill-formed if there is no such statement. The first use is fine; the second sits at the end of the switch. Clang rejects it, while GCC only warns, which is a permitted diagnostic but makes the third option tempting.

### Question 7 [standardese] ([dcl.attr.noreturn])

In C++23, is this translation unit well-formed?

```cpp
void stop();
[[noreturn]] void stop();
```

A. Ill-formed: the first declaration must specify `noreturn` if any declaration does
B. Well-formed: attributes accumulate across redeclarations
C. Ill-formed, no diagnostic required
D. Well-formed, and undefined behavior only if `stop` returns

**Answer (A):** Ill-formed: the first declaration must specify `noreturn` if any declaration does

**Why:** [dcl.attr.noreturn] says the first declaration of a function shall specify `noreturn` if any of its declarations does. Within one translation unit that is an ordinary diagnosable rule, and both GCC and Clang reject this. The no-diagnostic-required case is the cross-file one, where a function is declared `noreturn` in one translation unit and without it in another. Many other attributes, such as `deprecated`, may be added on a redeclaration, which is why the second option is tempting.

### Question 8 [standardese] ([intro.object], [dcl.attr.nouniqueaddr])

For an object `p` of type `Pair`, which of these does the C++23 standard guarantee?

```cpp
struct Empty {};

struct Pair {
  [[no_unique_address]] Empty a;
  [[no_unique_address]] Empty b;
  int i;
};
```

A. `sizeof(Pair) == sizeof(int)`
B. `(void*)&p.a == (void*)&p.b`
C. `(void*)&p.a != (void*)&p.b`
D. `sizeof(Pair) > sizeof(int)`

**Answer (C):** `(void*)&p.a != (void*)&p.b`

**Why:** [intro.object] allows two objects with overlapping lifetimes to share an address only if one is nested in the other, or at least one is a zero-size subobject and their types are not similar. `a` and `b` have the same type, so their addresses must differ even though both may be zero-size. Neither size claim is guaranteed: the attribute only permits overlap, and MSVC ignores it entirely.
