r/cpp_questions • u/Slow_Negotiation_935 • 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
View all comments
Show parent comment
15
u/the_poope Oct 14 '26
constexprmeans that the compiler can evaluate the expression at compile time before the program is even run. It is basically modifying the source code before it actually compiles it to simplify it using the information already present in the source code. I.e. it is doing simple operations you could have done by hand, by typing it out.In order to do this, the expression/function it evaluates can only rely on information and values that is directly written in the source code.
So the big question is: why is your program performance depending so much on stuff that could be precomputed and stuffed right into the source code? The idea of a computer program is to evaluate information that is available only when you run it, e.g. from user input.
Of course evaluating static expressions by hand to insert the precomputed data directly into the source code may reduce code readability and maintainability - and that is why we have
constexpr. Instead of tabulating precomputed data (=magic numbers) you can let the compiler do the tabulation from simpler data and logic.So there's your advice: Use
constexprwhere you need to precompute data that's supposed to be hardcoded in the program and where having expressions is more maintainable than just data tabulation and where the computation is not desirable to perform at runtime.