C++ for Embedded · Interview question

Why is constexpr especially valuable on a microcontroller?

A strong answer

Two concrete wins. First, zero runtime cost: anything computed at compile time, a derived baud-rate divisor, a CRC or sine lookup table, a gamma curve, costs the device no cycles, because the compiler did the work and the result is a constant in the instruction stream or a pre-filled table. Second, memory placement: a constexpr/const table with static storage lives in .rodata, which is mapped to flash, so it consumes no scarce RAM. The alternative, computing the table at boot in a runtime loop, costs both boot-time cycles and RAM to hold it. On a part with 20 KB of RAM and 256 KB of flash, pushing constant data into flash and eliminating boot computation is a direct, measurable resource win. It's the C++ way to get the benefits of a hand-maintained const table without hand-maintaining it.

What a weak answer sounds like

You know the answer. Do you know what gets you dinged?

Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.

From the lesson

const Correctness & constexpr

const propagates read-only intent through your whole API; constexpr moves computation to compile time so lookup tables and config land in flash with zero runtime cost.

More const Correctness & constexpr questions

Browse all 472 interview questions
Why is constexpr especially valuable on a microcontroller? | EmbeddedPrep.io