Reputation: 283
This is a follow up question to this one.
From one of the answers in the question linked, it makes sense that the purpose of declaring a variable as constexpr
is not truly to inform the compiler of the possibility of using that variable as a constant expression (although this is the end behavior of the compiler) but rather to convey to other programmers the intent that the variable can be used in a constant expression. My question is whether there is any benefit, performance or otherwise, to declaring a variable as constexpr
if the variable is not intended to be used in a constant expression (e.g. a constant member variable of a class which only appears in non-constant expressions with other non-const member variables). Also assume that this is not for an embedded system.
I work with code where the previous developers seem to use constexpr
like it's candy even when it's not clear that the intent is for the variable to be used in a constant expression (like in the example from the previous paragraph). I want to know if they knew something that I don't.
Upvotes: 1
Views: 292
Reputation: 25602
Yes, constexpr
variables are useful for more than just conveying intent and using in other constant expressions.
If you mark a variable constexpr
, the compiler will enforce that it itself is initialized with a constant expression. You can use this to make sure that the things you expect to be evaluated at compile time actually are. For example:
constexpr int constexpr_function() { return 123; }
int expensive_runtime_function() { return 123; }
void f()
{
constexpr int good1 = constexpr_function(); // OK.
// constexpr int good2 = expensive_runtime_function(); // Good: error.
const int bad1 = constexpr_function(); // OK.
const int bad2 = expensive_runtime_function(); // Bad: unexpected runtime cost.
}
Upvotes: 0
Reputation: 206717
but rather to convey to other programmers the intent that the variable can be used in a constant expression.
This is a matter of opinion but I beg to differ.
In principle, I think it is better to make everything that can be known and computed at compile time a constexpr
. The fact that it can also be used in constant expressions is a side benefit. Use of constexpr
may have performance related benefits too.
The key point I want to make is that "the value is known at compile time" is a characteristic of the variable/data. It is better to capture that characteristic by using a language provided feature. The only time one could justify not using it will be if there are any adverse side effects.
Upvotes: 1