</>EmbeddedInterview

What are constexpr and consteval?

MediumC++ for Embedded

Short answer: constexpr marks variables and functions that can be evaluated at compile time; when used where a constant is required (array sizes, template arguments, static_assert, constexpr variables), the compiler must evaluate them, so lookup tables, register values and configuration checks cost no run-time code or RAM. consteval (C++20) marks functions that must be evaluated at compile time — calling one with run-time values is an error. constinit (C++20) guarantees a variable is initialised statically (no run-time constructor, no initialisation-order problems).

#include <array>
#include <cstdint>
#include <cstdio>

constexpr uint32_t SYSCLK = 84'000'000;

void baud_rate_out_of_range();                       // not constexpr: calling it at compile time is an error

consteval uint32_t baud_div(uint32_t baud)           // must be compile time
{
    uint32_t div = (SYSCLK + baud / 2) / baud;
    if (div < 16 || div > 0xFFFF) baud_rate_out_of_range();   // error checks become compile errors
    return div;                                      // (works with -fno-exceptions, unlike throw)
}

constexpr std::array<uint8_t, 256> make_crc8_table()
{
    std::array<uint8_t, 256> t{};
    for (int i = 0; i < 256; i++) {
        uint8_t c = static_cast<uint8_t>(i);
        for (int b = 0; b < 8; b++) c = (c & 0x80) ? static_cast<uint8_t>((c << 1) ^ 0x07) : static_cast<uint8_t>(c << 1);
        t[i] = c;
    }
    return t;
}

constexpr auto CRC8_TABLE = make_crc8_table();       // computed by the compiler, placed in flash
static_assert(CRC8_TABLE[1] == 0x07, "table check");

constinit uint32_t uart_brr = baud_div(115200);      // static init, no constructor at startup

int main()
{
    std::printf("BRR=%u crc[0x31]=0x%02X\n", (unsigned)uart_brr, CRC8_TABLE[0x31]);
}

Why it is useful in firmware

  • Tables (CRC, sine, gamma, calibration curves) generated at compile time end up in flash, not RAM, with no start-up cost.
  • Configuration errors (impossible baud rates, PLL settings out of range, buffer sizes not powers of two) become compile errors via static_assert or consteval.
  • Replaces many macros with type-safe functions.

Note: a constexpr function called with run-time arguments simply runs at run time; to force compile-time evaluation, assign the result to a constexpr variable or use consteval.