Search code examples
c++gccconstantsconstexpr

constexpr variable use const variable at initialization


Why the following example compile with no problems?

#include <iostream>
int main(){
  
  const int var1 = 2;
  constexpr int var2 = var1 * 5;

return 0;
}

According to theory: “Variables” that are not constant expressions (their value is not known at compile time)

I used gcc compiler, can be the case that each compiler behave different?

Then how const var1 is known at compile time in this example?

I found other topics about const vs constexpr but I still don't understand it.


Solution

  • Why the following example compile with no problems?

    The full-expression of any constexpr variable has to be a constant expression, i.e evaluable at compile-time.

    Your initializer var*5 is a constant expression because var is const-qualifed integral type that is itself initialized by integral constant expression; also 5 is also an integral constant expression, hence, the full-expression var*5 is also a constant expression. So nothing will cause the program to be ill-formed.