If you are learning C++20, you are likely to know the attribute [[likely]] and [[unlikely]] which are introduced in C++20.
These attributes are standard tools for giving the compiler a hint about which branch of a conditional statement is more probable to execute. They do not change the program's logic, but allow the optimizer to arrange code in a way that favors the expected path for better performance.
These attributes are essentially a portable, standard replacement for non-standard compiler extensions like __builtin_expect. In the old days, when you want to give your compiler a hint. You will usually use likely() from the linux kernel.
For example, the linux kernel has defined a wrapper for __builtin_expect
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
Syntax and Usage Rule
if (condition) [[likely]] {
// This block is expected to execute most of the time
} else [[unlikely]] {
// This block is a rare path
}
Notice the attribute goes on the statement, not the condition. Writing if ([[likely]] condition) is a syntax error—the attribute precedes the substatement, meaning the block or single statement that follows ).
What it does?
A common misconception is that [[likely]] and [[unlikely]] whisper directly into the CPU's branch predictor. They don't. Modern high-end CPUs have sophisticated dynamic predictors that learn from runtime behavior; they don't care about your source-code hints .
What these attributes actually do is tell the compiler to arrange the generated machine code differently. The compiler might reorder basic blocks so that the "likely" path is a straight-line sequence of instructions with no taken branches, while the "unlikely" path gets pushed further away. This helps with instruction cache locality and front-end efficiency. Fewer taken branches means the CPU's fetch unit isn't jumping around memory, even if the branch predictor guessed correctly.
There's a secondary effect too: marking a path [[unlikely]] can discourage the compiler from performing if-conversion—replacing a branch with a conditional move (cmov) or similar branchless code. Sometimes a predictable branch is faster than branchless code, especially if the branchless version creates a longer dependency chain . If you know a branch is highly predictable, the attribute can nudge the compiler toward keeping the branch.
A quick way to see whether your compiler did anything: compile to assembly (gcc -S -O2, clang -S -O2) and look at the block ordering around the branch. If the likely block moved above the branch and the unlikely block sits after a jmp, the hint landed.
The switch Trap
The standard has a subtle rule for switch statements that catches people off guard. An execution path "includes" a label only if there is an actual jump to that label. Falling through from a previous case doesn't count .
switch (i) {
case 1: [[fallthrough]];
[[likely]] case 2: return 1;
default: return 2;
}
Here, i == 2 is considered likely, but i == 1—which falls through into case 2—gets no benefit from the attribute. If you wanted to hint that both 1 and 2 are common, you'd need to structure things differently. This is a classic "read the fine print" moment.
Here's the same trap in a more realistic shape, a state machine where two states share a handler:
Result step(State s) {
switch (s) {
case State::Idle:
prepare();
[[fallthrough]];
[[likely]] case State::Ready:
return run();
case State::Error:
return recover();
default:
return Result::Unknown;
}
}
State::Ready is hinted likely. State::Idle is not hinted, even though it flows into Ready—because the standard says a path "includes" a label only via an actual jump to it. If Idle is actually common in your workload, you need to restructure: either give Idle its own code path, or accept that the hint won't help it. You can't fix this by putting a second [[likely]] on the fallthrough—that's an attribute on a different label, and the standard treats each label's hint independently.
How to use it correctly?
The C++ standard itself includes a non-normative note warning that excessive use of these attributes is "liable to result in performance degradation" . That's not just lawyer-speak. Here's why:
-
Wrong hints hurt more than no hints. If you mark a branch
[[likely]]but it's actually taken 30% of the time, the compiler may lay out the code poorly, putting the truly common path behind a jump. You've made the common case slower to make the wrong case look pretty. -
Your error handling might not be rare. A validation function that rejects bad input might see that "unlikely" path quite often in real traffic. Marking every
throwor error return[[unlikely]]reflexively is a bad habit . -
The compiler might already know. Modern compilers (especially with
-O2/-O3) often treat throwing code paths as cold by default. Adding[[unlikely]]to an exception branch may do literally nothing .
The practical rule: don't sprinkle these around. Profile first. If a branch is genuinely a hotspot and you've measured that it's predictable, then consider a hint. And even then, compare the generated assembly and benchmark both versions on your target hardware .
Example: A Contract Check in a Hot Loop
The classic case: a function that's called millions of times and almost never fails.
bool process_item(const Item& item) {
if (item.is_valid()) [[likely]] {
// Fast path: 99.9% of calls end up here
do_work(item);
return true;
} else [[unlikely]] {
log_error("invalid item", item.id);
return false;
}
}
The compiler will keep do_work(item) as the fall-through path and push the log_error block out of line. In assembly, you'll typically see the unlikely block relocated after the function's hot body, sometimes with a cold section attribute applied. The hot path has zero taken branches at the if.
Example: Bounds Checking in a Parser
A tokenizer that spends nearly all its time inside the buffer, with the end-of-input check being rare:
while (true) {
if (pos < len) [[likely]] {
char c = buf[pos++];
// ... process character
} else [[unlikely]] {
break; // end of input
}
}
This is a real hot-loop shape. Marking the bounds check as likely tells the compiler that the loop body is the straight-line path. Without the hint, GCC at -O2 will often get this right anyway based on the loop structure, but with more complex conditions (multiple checks, function calls) it can lose the plot. This is exactly the kind of thing to benchmark before and after—the win here is usually in instruction cache behavior, not branch prediction.
Example: [[unlikely]] on a goto Label
Attributes can go on labels, not just statements. A pattern you'll see in kernel C code:
int parse(const char* p) {
if (!p) [[unlikely]] goto fail;
// ... lots of straight-line code
return 0;
fail:
return -1;
}
The hint on the goto label tells the compiler the fail block is cold, which is often true in parsers on the happy path. This works because the attribute is on a labeled statement, which is one of the allowed placements.
The cmov Problem
Here's a scenario where [[likely]] can be a lifesaver. Suppose you have a tight loop with a condition the compiler decides to compile branchlessly using cmov. Without PGO, GCC at -O3 sometimes makes this choice aggressively, guessing the branch is hard to predict. If the condition is actually almost always true (or almost always false), the cmov creates an unnecessary dependency chain and the loop runs slower than a simple branch would .
Adding [[likely]] or [[unlikely]] tells the compiler "hey, this is predictable," which can discourage the cmov and restore the branchy version. That's a real, measurable win—but only if you actually verify it with benchmarks.
A getter that returns a cached value is a good place to watch for this:
Value get_value() const {
if (cache_valid) [[likely]] {
return cache;
} else [[unlikely]] {
return compute_and_cache();
}
}
Short functions like this are where if-conversion bites. At -O3, GCC may compile this to a cmov or a select-like sequence, loading cache and calling compute_and_cache speculatively or building a dependency chain. If cache_valid is nearly always true, that's wasted work and a longer critical path. The [[likely]] hint discourages the if-conversion, keeping the slow call behind a real branch. Worth checking with objdump -d whether the cmov actually disappeared.
When it becomes a problem
Suppose you're writing a validation routine that runs on user input:
bool validate(const Request& r) {
if (r.has_auth_token()) [[likely]] {
// ...
}
if (r.body_size() < MAX) [[likely]] {
// ...
}
if (!r.contains_injection()) [[unlikely]] {
return false;
}
// ...
}
If this routine is called on every incoming request and a meaningful fraction are unauthenticated, oversized, or malicious, the "unlikely" hints are lying. The compiler may lay out the rejection paths far from the hot code, causing extra jumps on paths that are actually common. Worse, the [[likely]] on the first two checks may defeat if-conversion where branchless would have been fine. This is the "pessimization" the standard warns about. Profile before annotating—especially in input-validation code, which is often the opposite of rare.
Treat Hints as Reviewable Claims
One habit that pays off: if a branch is marked [[likely]], there should be a comment or a benchmark pointing at why.
Then when the workload changes and the claim goes stale, the annotation is easy to find and re-evaluate. Attributes with no justification tend to survive refactors long after they stop being true—which is exactly how you end up with a "likely" branch that's taken 40% of the time and code layout that's worse than the default.
A Minimal Benchmark Harness
Since the whole point is measurement, here's a tiny setup to compare a hinted and unhinted version of the same hot loop:
#include <benchmark/benchmark.h>
#include <vector>
// Variant A: with hints
static void BM_HotWithHints(benchmark::State& state) {
std::vector<int> v(state.range(0), 1); // mostly non-zero
for (auto _ : state) {
int sum = 0;
for (int x : v) {
if (x != 0) [[likely]] sum += x;
else [[unlikely]] sum -= 1;
}
benchmark::DoNotOptimize(sum);
}
}
BENCHMARK(BM_HotWithHints)->Range(1 << 10, 1 << 20);
// Variant B: without hints
static void BM_HotWithoutHints(benchmark::State& state) {
std::vector<int> v(state.range(0), 1);
for (auto _ : state) {
int sum = 0;
for (int x : v) {
if (x != 0) sum += x;
else sum -= 1;
}
benchmark::DoNotOptimize(sum);
}
}
BENCHMARK(BM_HotWithoutHints)->Range(1 << 10, 1 << 20);
BENCHMARK_MAIN();
Run with -O2 and -O3, and dump assembly for both. If the two variants produce identical machine code, the hint did nothing on your compiler/target—which is a perfectly normal outcome and tells you to stop worrying about it for that branch.
PGO
If you can use Profile-Guided Optimization, do that instead. PGO uses real execution data from a training run to optimize branch layout across the entire program, not just the branches you remembered to annotate. Likelihood attributes are a manual, local supplement for situations where PGO isn't practical—embedded systems with tight build constraints, libraries that ship to many different workloads, or a quick fix for one critical branch you've already profiled .
A Quick Reality Check
If you take one thing from this, make it this: [[likely]] and [[unlikely]] are code generation hints, not branch predictor commands. They're most useful when:
- You've profiled and found a genuinely hot, predictable branch.
- The compiler is making a bad layout or if-conversion decision without the hint.
- You've verified the hint helps on your actual compiler and target.
Otherwise, leave them alone. The default behavior is usually fine, and a wrong hint is worse than no hint at all.
Top comments (0)