What is a value known at compile time ?
I think it makes more sense to talk about constant expressions. A constant expression has a value that is known at compile time. Roughly speaking, it may be simply a literal, the name of another variable (whose value again is known at compile time) or a complex expression involving sub-expressions with values known at compile time.
The quote states that the initializer of a variable declared with constexpr
needs to be a constant expression. In particular there are requirements an expression must satisfy to be a constant expression; Those are listed here.
Examples are
constexpr int i = 54;
constexpr float f = 684; // Compile-time conversion from int to float
constexpr int func( int i )
{
return i*47 % 23;
}
constexpr auto value = func(i * f); // Okay; constexpr function called
// with arguments that, when substituted inside,
// yield constant expressions
Sometimes a value is actually known at compile time but the expression isn't a constant one according to standard. That includes
int i = 43;
constexpr int j = reinterpret_cast<int>(i); // Shouldn't compile. (Does with GCC)
There are cases were the compiler may do constant folding - some values can be computed at compile time but don't have to be.
int i = 0;
for (int j = 1; j != 10; ++j)
i += j;
return i;
The compiler can completely eliminate the loop and initialize i
with 55
(or simply return 55
and eliminate i
too) as long as the behavior stays the same. This is known as the as-if rule.