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

constexpr

Use case

Compile-time buffer sizes and calculations.

Explanation

constexpr values and functions can be evaluated at compile time. Array sizes, templates and static_assert all require compile-time constants. The same constexpr function works at compile time (for smallBuffer size) and runtime (with count variable).

Code

#include <cstdint>
#include <iostream>

constexpr size_t ARM64_INST_SIZE = 4;
constexpr size_t MAX_INSTS = 100;
constexpr size_t BUFFER_SIZE = ARM64_INST_SIZE * MAX_INSTS;

constexpr size_t calcBufferSize(size_t instCount) {
  return ARM64_INST_SIZE * instCount;
}

int main() {

  uint8_t buffer[BUFFER_SIZE];
  uint8_t smallBuffer[calcBufferSize(10)];

  size_t count = 50;
  size_t runtimeSize = calcBufferSize(count);

  std::cout << "Buffer size: " << sizeof(buffer) << "\n";
  std::cout << "Small buffer size: " << sizeof(smallBuffer) << "\n";
  std::cout << "Runtime calc: " << runtimeSize << "\n";

  return 0;
}

View on GitHub.

Output

$ ./src/c++11/build/constexpr
Buffer size: 400
Small buffer size: 40
Runtime calc: 200