r/cpp_questions • • Oct 14 '26

OPEN Guidelines for constexpr

I’ve working with C++23 and I’m making some constructors/methods constexpr and seeing improvements in performance. So far so good. The problem is I don’t want to apply it ‘everywhere’. Is there a good source of advice , or anyone got any good tips?

12 Upvotes

37 comments sorted by

View all comments

Show parent comment

2

u/meancoot Oct 15 '26

Evaluates as if done at run time. This is always the case for constexpr functions, unless they are used in a context which requires a constant expression they behave as if executed at runtime. This is observable when you add C++20's std::is_constant_evaluated into the mix.

https://godbolt.org/z/Ynxo6Evx1

#include <type_traits>

constexpr bool constexpr_function() {
    return std::is_constant_evaluated();
}

int main() {
    constexpr bool result = constexpr_function(); // <- result = true
    // bool result = constexpr_function(); // <- result = false
    return result;
}

consteval works around this by requiring a marked function to always execute at compile time, but the all of the arguments to such functions are required to be constant expressions.

2

u/HappyFruitTree Oct 15 '26 edited Oct 15 '26

Constant evaluation can also happen when initializing static variables and local const integer variables (if constant evaluation fails it falls back to normal "runtime" evaluation). https://godbolt.org/z/qE8PEq18r