In many microcontrollers, periodic interrupts (1 ms, 10 ms, 100 ms, etc.) are generated using a hardware timer reload value.
This value must be computed using:
reload = timerClockHz × intervalSec
Since this value must be exact, firmware often computes it at compile time using constexpr.
Incorrect reload values cause jitter, drift, or system failure.
Your job is to compute the correct timer reload count at compile time for different timer intervals.
What you must do:
constexpr function named computeReload(clockHz × intervalMs + 500) / 1000 +500 is used for integer roundingconstexpr array named RELOAD_TABLEcomputeReloadtimerClockHz = 1'000'000 (1 MHz)Program input:
0 → 1 ms reload1 → 10 ms reload2 → 100 ms reloadProgram output:
RELOAD_TABLE[index]
Example 1
Input:
1
Output:
10000
Example 2
Input:
2
Output:
100000
Constraints:
computeReload must be declared constexprRELOAD_TABLE must be declared constexpr
In Embedded C, we often use macros (#define) to perform math before the code runs (e.g., #define PRESCALER (CLK / BAUD)).
In C++, constexpr (Constant Expression) allows you to write standard C++ functions and variables that the compiler evaluates during compilation.
This means complex calculations (like generating CRC tables or converting units) happen on the developer's PC, and only the final result is burned into the microcontroller's Flash memory.
1. Variables (True Constants)
Unlike const (which just means "read-only" and might typically sit in RAM or Flash), constexpr guarantees the value is known at compile time.
// C-Style
#define MAX_VOLTAGE 3.3
// C++ Style
constexpr float MAX_VOLTAGE = 3.3f;
constexpr float THRESHOLD = MAX_VOLTAGE / 2.0f;
// Compiler calculates 1.65f and stores it directly. No runtime division.2. Functions (The Powerhouse)
You can write functions that execute during compilation.
// Calculates factorial at compile-time
constexpr int factorial(int n) {
return (n <= 1) ? 1 : (n * factorial(n - 1));
}
// Usage
// The compiler effectively writes: int buf_size = 120;
int buf_size = factorial(5); 3. If/Loops (C++14 onwards)
Modern constexpr supports standard logic.
constexpr uint32_t calculate_prescaler(uint32_t sysclk, uint32_t target_freq) {
uint32_t div = sysclk / target_freq;
if (div > 0xFFFF) return 0xFFFF; // Clamp to 16-bit
return div;
}| Feature | #define | const | constexpr |
|---|---|---|---|
| Mechanism | Text Replacement. | Read-Only Variable. | Compile-Time Calculation. |
| Type Safety | None. | Strong. | Strong. |
| Debug | Hard (Symbol usually lost). | Easy. | Easy (if runtime fallback). |
| Memory | None (Code literal). | RAM or Flash. | None (Code literal). |
1. Zero-Overhead Lookup Tables
Instead of hardcoding a 256-byte CRC table or Sine Wave array (which is error-prone to type manually), you can write a constexpr function to generate it. The compiler fills the array in Flash for you.
struct Table { uint8_t data[256]; };
constexpr Table generate_crc() {
Table t = {};
// ... Fill t.data logic ...
return t;
}
// Table is generated during compilation and stored in Flash (.rodata)
constexpr Table crc_table = generate_crc(); 2. Safe Register Math
Calculating bitmasks or clock dividers often involves complex shifts and divisions. Using macros (#define) is messy and error-prone. constexpr functions allow you to write readable logic with validation checks (asserts) that run at compile time.
3. Static Assertions
You can use constexpr values in static_assert to prevent invalid configurations from even compiling.
constexpr int BUFFER_SIZE = 128;
static_assert(BUFFER_SIZE % 8 == 0, "Buffer must be aligned to 8 bytes");| Pitfall | Details |
|---|---|
| ❌ Runtime Usage | A
|
| ❌ Debugging | You cannot "step through" a constexpr calculation in the debugger because it happened before the program started. |
| ❌ Complexity Limit | Compilers place limits on how many steps a constexpr function can take (recursion depth or loop count) to prevent the compilation from hanging forever. |
✅ Use consteval | In C++20, the keyword consteval was added. It forces immediate evaluation and throws an error if it attempts to run at runtime. |