C++ constexpr Keyword
Example
Calculate a value when the program is compiled:
constexpr int square(int x) {
return x * x;
}
int main() {
constexpr int myNum = square(5);
cout << myNum;
return 0;
}
Definition and Usage
The constexpr keyword specifies that the value of a variable or function can be calculated when the program is compiled, not when it runs. This can make the program faster.
A constexpr variable is also const, so it cannot be changed. Its value must be known when the program is compiled, so you can only use fixed values, other constexpr variables and constexpr functions.
A constexpr function can also be called with normal variables. Then it runs like a normal function, while the program runs.
Related Pages
Read more about constants in our C++ Constants Tutorial, and about functions in our C++ Functions Tutorial.