Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clang doesn't evaluate the value of the constexpr function for the non-constexpr variable at compile time

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?

like image 986
TupleCats Avatar asked Apr 29 '19 08:04

TupleCats


2 Answers

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;
like image 95
lubgr Avatar answered Nov 10 '22 22:11

lubgr


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.

like image 23
P.W Avatar answered Nov 10 '22 20:11

P.W