Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The [[unlikely]] attribute is a C++20 standard optimization hint that informs the compiler that a specific execution path is statistically improbable. By applying this attribute to a statement or label, developers instruct the compiler’s backend to de-prioritize the associated branch during instruction scheduling, basic block placement, and static branch prediction.

Compiler Behavior

When a compiler encounters [[unlikely]], it typically alters the generated machine code in the following ways:
  • Basic Block Placement: The compiler moves the “cold” (unlikely) basic blocks out of the primary linear execution path. This improves instruction cache (i-cache) locality for the “hot” path by preventing the CPU from fetching instructions that will rarely be executed.
  • Branch Prediction: The compiler may emit specific branch prediction prefixes (depending on the target architecture) or structure conditional jumps such that the fall-through path aligns with the likely execution flow.

Syntax and Placement

The attribute appertains to the statement or label it immediately precedes. It is most commonly applied to conditional branches (if statements) and switch cases. Conditional Statements: When applied to an if or else branch, the attribute must precede the statement block.
if (condition) [[unlikely]] {
    // Compiler assumes this block is rarely executed
    execute_cold_path();
} else {
    // Compiler assumes this is the dominant path
    execute_hot_path();
}
It can also be applied to the else branch directly:
if (condition) {
    execute_hot_path();
} else [[unlikely]] {
    execute_cold_path();
}
Switch Statements: In a switch block, the attribute appertains to the case or default label.
switch (value) {
    case 1:
        process_standard();
        break;
    [[unlikely]] case 2:
        process_anomaly();
        break;
    default:
        process_default();
        break;
}
Iteration Statements: It can be applied to loop bodies to indicate that the loop will rarely execute or will terminate quickly.
while (condition) [[unlikely]] {
    process_rare_event();
}

Technical Constraints

  • Non-binding Hint: The attribute is strictly a heuristic hint. The C++ standard does not mandate any specific optimization, and compilers are permitted to ignore it entirely, especially if Profile-Guided Optimization (PGO) data contradicts the attribute.
  • Mutually Exclusive: A single statement or label cannot be marked with both [[likely]] and [[unlikely]].
  • Statement-Level Only: The attribute applies to statements and labels, not to expressions or declarations. Applying it to a boolean expression directly (e.g., if ([[unlikely]] x > 5)) is syntactically invalid.
Master C++ with Deep Grasping Methodology!Learn More