Item 15 of Scott Meyer's Modern C++ book: "use constexpr whenever possible". He says you can mark a function constexpr and still call it with values that aren't known at compile-time -- in that case it'll behave like any other runtime function, so you get the benefits of compile-time computation if possible but can still use it with non-compile time values too. The compiler will figure it out. But if that's true, then why can't we tag every function with constexpr (or better yet, don't tag any of them and let the compiler figure it out all the time)? If the compiler is able to detect whether the values are known at compile-time and automatically do the right thing when I tag the method as constexpr, then why can't it automatically do that same check even when I don't write constexpr?
Asked
Active
Viewed 165 times
3
-
1`constexpr` only works for functions that do not depend on any runtime state. – SLaks Sep 30 '16 at 15:38
-
1I would say that its the same reason for regular old const, its part of your interface, what if I make a change to a function that is const which attemps to modify state? I get a compiler error. Same thing for constexpr, I'm saying "this should be constexpr". Theres probably other (more valid) reasons but this is one I can think of. – Borgleader Sep 30 '16 at 15:41
1 Answers
0
... when the function receives values which are not known in compile-time. You cannot mark a function to be constexpr
if its computation depends on the value of a pointer, or a global value, etc, etc.
If the body
of that function can be executed in compile time, you can mark it as constexpr
, but you can still call it with runtime values. E.g., to be used for both, to calculate a static const value of a parametric class, using a compilation-time value passed as parameter, but also, to calculate a user value after getting its parameter through std::cin
.
whenever possible
... if the function body uses I/O operations, non-const global/static/-member) values, addresses or volatile
s, to name a few, is not possible.

ABu
- 10,423
- 6
- 52
- 103
-
No, that's not true. You certaintly *can* mark a function constexpr even if it depends on a pointer or global value. (The constexpr would then be useless cause everything is computed at runtime, but it compiles and runs fine). But this compiles fine: "constexpr int f(int* y) { return *y; }" – user2543623 Sep 30 '16 at 16:18