Some code:
constexpr int sum(int a, int b) {
return a + b;
}
int main() {
int a = sum(4, 5);
return 0;
}
I compile this code with clang-9
but it doesn't evaluate the value of int a
in main function at compile time.
If i use constexpr int a
clang evaluates it at compile time but i can't change this variable at runtime.
But gcc-7.1
evaluate the value of int a
at compile time.
Why is this happening? How to fix it?
When you want a value to be precomputed at compile time but then bound to an identifier which allows for modification, you can only force this by initializing a non-constexpr
object with a constexpr
object:
constexpr int init = sum(4, 5);
int a = init;
constexpr
specifier only means that it is possible to evaluate the value of the function at compile time. It does not mean that it should be evaluated at compile time. So different compilers/versions have flexibility in this matter.
If you want to enforce such evaluation at compile time, then the variable it is assigned to should also be constexpr
.
This happens when a
is constexpr int
and not just a plain int
.
To fix your particular issue, you should use an intermediate variable which is constexpr
and then assign its value to a variable that can be changed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With