by 38 · 2y ago · 0 comments
Also "a computation is not and cannot be constant" depends on what is meant precisely by "computation" and "constant." Is "23 * 48" a constant, or is it a computation? What about "2208/2"? What about "1.104e3"?
You can define "constant" as "something that is not computed but that exists in the program as an immediate value." In that case you're right but only by definition. And the compiler must still "interpret" the immediate value. It's a slightly fuzzy distinction in my eyes.
Sure it can - but you know that - a compile time computation can be a run time constant. There’s loads of reasons to want constant values built out of compile-time computation. You haven’t had to write any high performance code?
Start with something like
constexpr float angle_threshold = 45.0f;
constexpr float degToRad = M_PI / 180.0f;
constexpr float x_threshold = cosf( angle \* degToRad );
The nice thing about having this be an expression is it’s semantic, and I can tune my angle in degrees, not have some raw number that isn’t adjustable.Maybe I need a small table of these, suddenly running a little code at compile time looks great. Doing it during compilation is a lot nicer than having a script dependency and having to write a build step for it.
The bigger issue with constexpr specifically is that it doesn’t actually guarantee compile time evaluation…
But I don't believe one can justify the existence of constexpr simply by pointing to code that absolutely any compiler would make into constants absent it.
Perhaps in your example one could say that the value is that you really want the compilation to abort should changes happen to the code that make it impossible for the compiler to turn it into constants, since doing so is performance critical-- I think that would be a fair point.