A constant expression is a reference to an value does not changeAnd in The results can be calculated during the compilation processexpression that can be compile-time evaluationThe expression.
Example 1:
#include <iostream>using namespace Std;int main () {const INT a1 = Ten; A1 is a constant expression. const INT a2 = a1 +; A2 is a constant expression int a3 = 5; A3 is not a constant expression const int a4 = A3; A4 is not a constant expression, because the execution of the A3 program is initialized when it arrives at the declaration where it is located, so the value of the variable A4 is not known until the program runs. But compile no problem! return 0;}
The above code compiles normally.
Indicates that a const declaration is not necessarily a constant expression!
C++11 The new standard specifies that a variable is allowed to be declared as a constexpr type so that the compiler can verify that the value of the variable is a constant expression . The constexpr
specifier declaration can obtain the value of a function or variable at compile time , and a variable declared as constexpr must be a constant and be initialized with a constant expression.
Example 2:
#include <iostream>using namespace Std;int main () {const INT a1 = Ten; A1 is a constant expression. const INT a2 = a1 +; A2 is a constant expression int a3 = 5; A3 is not a constant expression constexpr int a4 = A3; A4 is not a constant expression, because the execution of the A3 program is initialized when it arrives at the declaration where it is located, so the value of the variable A4 is not known until the program runs. Compile Error! return 0;}
constexpr int a4 = A3; Compile will error!
Example 3:
#include <iostream>using namespace Std;int main () {const INT a1 = Ten; A1 is a constant expression. const INT a2 = a1 +; A2 is a constant expression int a3 = 5; A3 is not a constant expression const int a4 = A3; A4 is not a constant expression, because the execution of the A3 program is initialized when it arrives at the declaration where it is located, so the value of the variable A4 is not known until the program runs. Compile Error! Char ARR1[A2]; No problem char arr2[' y ']; No problem, ' Y ' ASCII code is 121, equivalent to Char Arr2[121];char ARR3[A4]; Compile an error because A4 is not a constant expression return 0;}
Related articles:
Share instances of multiple C # common regular expressions
PHP definition constants are, the difference between const and define