skip to content

In C++20, what do the [[likely]] and [[unlikely]] attributes actually change in generated code, and how do teams misuse them?

level: seniorimportance: should knowfreq 35%

answer

  1. on a statement or label
  2. code layout, not the predictor
  3. fall through on the hot path
  4. the standard warns about excess
  5. measure, or let a profile decide

basics

~20 s

C++20's [[likely]] and [[unlikely]] mark a statement or label as the hot or cold path, so the compiler makes the hot path the fall-through and moves the cold one out of line. They do not program the CPU's branch predictor.

solid answer

~50 s

The attributes apply to **statements and labels**: `if (v < 0) [[unlikely]] { ... }` or `[[likely]] case 2:`; written inside the condition, Clang rejects them. They tell the compiler that paths through the marked statement are arbitrarily more (or less) likely, and compilers use that for **block placement and optimisation priority**: the likely path falls straight through, the unlikely path moves out of line, and cold code may be optimised for size. They do not set the processor's branch predictor, which learns from run-time history. Misuse is common: hints on 50/50 branches, hints from intuition instead of a profile, `[[likely]]` on both arms (Clang ignores conflicting hints with a warning), or a hint that went stale when the data changed. The standard itself notes that excessive use is liable to degrade performance. Profile-guided optimisation usually beats hand-written hints.

code

cpp · 15 lines
cpp
void logError(int);
int scale(int v) {
  if (v < 0) [[unlikely]] {
    logError(v);
    return 0;
  }
  return v * 3;
}
int scaleWrong(int v) {
  if (v < 0) [[likely]] {
    logError(v);
    return 0;
  }
  return v * 3;
}

go deeper

for a junior

Recognise the C++20 attributes and that they are hints about which path is common, placed on a statement or case label.

for a middle

Explain that they affect code layout and optimisation weighting, not the run-time predictor, and show correct placement.

for a senior

Treat them as measured exceptions: verify bias with a profile, compare assembly and timing, and remove stale or balanced-branch hints.

for a principal

Set the policy: prefer profile-guided optimisation in shipping builds and allow hand hints only on rare-by-construction paths.

## Where the attributes go C++20 added `[[likely]]` and `[[unlikely]]`. Both may be applied to **labels or statements**, take no arguments, and cannot appear together in one attribute list. ```cpp if (v < 0) [[unlikely]] { // on the substatement of the if logError(v); return 0; } switch (n) { [[likely]] case 2: f(); break; // on a case label default: g(); } ``` Two placements that do not work: - **Inside the condition.** `if ([[likely]] x > 0)` is rejected; Clang reports `an attribute list cannot appear here`. - **On both arms.** `if (x > 0) [[likely]] ... else [[likely]] ...` compiles, but Clang warns `conflicting attributes 'likely' are ignored [-Wignored-attributes]` and drops both. Before C++20, GCC and Clang offered the builtin `__builtin_expect(cond, expected)`, which annotates the condition rather than the statement; it is still common in older code bases. ## What the compiler does with them The standard's note says the attributes are intended to let implementations optimise for paths that include a `[[likely]]` statement being **arbitrarily more likely** than paths that do not. In practice compilers use that to: 1. **Lay out code** so the hot path is the fall-through and the cold path sits after the hot path's return. 2. **Weight other decisions**, such as which calls on the hot path are worth inlining and which code is optimised for size. The x86-64 listing below shows the first effect. With `[[unlikely]]` on the error branch, the function tests the sign, jumps away only for negative input and otherwise falls through to `v * 3` and returns. With the hint inverted, the common case is the one that takes the jump. ## What they do not do - They do **not** set the processor's branch predictor. Modern predictors learn from the history of each branch at run time; a well-predicted branch costs little whether it is taken or not, and the attribute does not change what the CPU predicts. - They do **not** change behaviour: the program does the same thing with or without them. - They do **not** help a branch that is truly unpredictable; for that, the fix is branchless code or a different data order, not a hint. ## How teams misuse them 1. **Hints from intuition.** A branch someone believed rare turns out to run 30 percent of the time in production, and the hint moves real work out of line. 2. **Hints on balanced branches.** On a 50/50 branch any layout is wrong half the time; the hint only adds noise. 3. **Stale hints.** The data changes, the code is reused elsewhere, and nobody revisits the annotation. 4. **Blanket annotation.** The standard warns that excessive usage of either attribute is liable to result in performance degradation; marking everything also hides the few hints that matter. ## Where they earn their place - Error and validation paths that are rare **by construction**: allocation failure, malformed input in a parser that normally sees valid data, assertion failures. - A dominant `case` in a dispatch `switch`, confirmed by measurement. - Code where a profile is not available in the build that ships. ## Checking a hint yourself 1. Compile the function with and without the attribute at `-O2 -S` and diff the output: if the block order did not change, the hint did nothing on that compiler. 2. Time the function on production-shaped input both ways; the layout effect is real but small, so a change within noise means the attribute is decoration. 3. Count how often the branch actually goes each way, with a counter in a test build or a profiler's branch statistics, before trusting a hint someone wrote years ago. When a representative workload exists, **profile-guided optimisation** gives the compiler measured branch frequencies for every branch, which is usually better than hand annotation; its flags are the compiler's business. Whatever is chosen, compare the generated code and the timing before and after: an attribute that changes neither should be deleted.

  • Does [[unlikely]] on an error branch slow the error path down?
    Usually by a little: the error path now takes a jump to out-of-line code and may be optimised for size. That is the trade the attribute asks for. If the error path is itself latency-sensitive, for example a rejection that must be sent quickly, the hint is wrong for that code even though the branch is rare.
  • How would you decide whether to keep an existing [[likely]] annotation in a hot function?
    Measure how often the branch goes each way under a production-like workload, compare the generated code with and without the attribute, and time the function both ways. Keep it only if the branch is strongly biased in the marked direction and the timing improves; otherwise delete it or let profile-guided optimisation decide.

Like a road built so the everyday route runs straight ahead and the rare exit sits behind a turn: drivers still choose at every junction, but the common trip is smoother. The hint shapes the road, not the driver.

  • [[likely]] tells the CPU which way to predict the branch at run time.
  • The attribute goes inside the condition: if ([[likely]] x > 0).
  • Marking both branches [[likely]] makes the whole if statement faster.
  • More [[likely]] annotations can only help, never hurt.
  • [[unlikely]] lets the compiler assume the branch is never taken and delete it.

Assumes C++20 or later: [[likely]] and [[unlikely]] were added in C++20 (__has_cpp_attribute value 201803L); older code uses the __builtin_expect builtin.