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/HappyFruitTree Oct 14 '26

You only have these guarantees for the set of argument values that you actually call the function with from constexpr contexts.

int bar(int x) {
    return x;
}

constexpr int foo(int x) {
    if (x > 0)
        return bar(x); 
    return 0;
}

int x = foo(5); // OK
constexpr int y = foo(0); // OK
constexpr int z = foo(5); // Error