Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

[[assume]] attribute

Use case

Help compiler optimize with known invariants (a condition that is always true at a certain point in your code).

Explanation

[[assume(expr)]] tells the compiler the expression is always true. Enables aggressive optimizations. UB if assumption is violated at runtime.

Code

#include <cstdint>
#include <print>

// https://en.wikipedia.org/wiki/Mach-O
bool is64Bit(uint32_t magic) {
  [[assume(magic == 0xFEEDFACE || magic == 0xFEEDFACF)]];
  return magic == 0xFEEDFACF;
}

int main() {
  uint32_t magic = 0xFEEDFACF;
  std::println("64-bit: {}", is64Bit(magic));
  return 0;
}

View on GitHub.

Output

$ ./src/c++23/build/assume-attribute
64-bit: true