Home > Article > Backend Development > Distinguish between C++ constant expressions, const, and constexpr (with code)
A constant expression is an expression whose value will not change and the calculation result can be obtained during the compilation process. It can be evaluated at compilation time expression.
Example 1:
#include <iostream> using namespace std; int main() { const int a1 = 10; // a1是常量表达式。 const int a2 = a1 + 20; // a2是常量表达式 int a3 = 5; // a3不是常量表达式 const int a4 = a3; // a4不是常量表达式,因为a3程序的执行到达其所在的声明处时才初始化,所以变量a4的值程序运行时才知道。但编译没问题! return 0; }
The above code can be compiled normally.
It shows that what is declared by const is not necessarily a constant expression!
The new C 11 standard stipulates that variables are allowed to be declared as constexpr type so that the compiler can verify whether the value of the variable is a constant expression. constexpr
Specifier declaration can obtain the value of a function or variable at compile time. A variable declared as constexpr must be a constant and must be initialized with a constant expression.
Example 2:
#include <iostream> using namespace std; int main() { const int a1 = 10; // a1是常量表达式。 const int a2 = a1 + 20; // a2是常量表达式 int a3 = 5; // a3不是常量表达式 constexpr int a4 = a3; // a4不是常量表达式,因为a3程序的执行到达其所在的声明处时才初始化,所以变量a4的值程序运行时才知道。编译报错! return 0; }
constexpr int a4 = a3; Compilation will report an error!
Example 3:
#include <iostream> using namespace std; int main() { const int a1 = 10; // a1是常量表达式。 const int a2 = a1 + 20; // a2是常量表达式 int a3 = 5; // a3不是常量表达式 const int a4 = a3; // a4不是常量表达式,因为a3程序的执行到达其所在的声明处时才初始化,所以变量a4的值程序运行时才知道。编译报错! char arr1[a2]; // 没问题 char arr2['y']; // 没问题,'y'的ASCII码为121,相当于 char arr2[121]; char arr3[a4]; // 编译报错,因为a4不是常量表达式 return 0; }
Related articles:
Share multiple examples of commonly used regular expressions in C
#PHP defines constants, the difference between const and define
The above is the detailed content of Distinguish between C++ constant expressions, const, and constexpr (with code). For more information, please follow other related articles on the PHP Chinese website!