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

[[likely]] and [[unlikely]] attributes

Use case

Hint to optimizer for branch prediction.

Explanation

Hints for branch prediction. Does not change semantics (meaning of the code), may improve performance.

Code

#include <cstdint>
#include <iostream>

// https://en.wikipedia.org/wiki/Mach-O
bool isMachO(const uint8_t *data) {
  uint32_t magic = *reinterpret_cast<const uint32_t *>(data);

  if (magic == 0xFEEDFACF) [[likely]] {
    return true;
  } else if (magic == 0xFEEDFACE) [[unlikely]] {
    return true;
  }
  return false;
}

int main() {
  uint8_t data[] = {0xCF, 0xFA, 0xED, 0xFE};
  std::cout << "Is Mach-O: " << std::boolalpha << isMachO(data) << "\n";
  return 0;
}

View on GitHub.

Output

$ ./src/c++20/build/likely-unlikely-attributes
Is Mach-O: true