What is the difference between const and constexpr in C++?
| Point | const | constexpr |
|---|---|---|
| Meaning | Read only after the start | Computed at compile time |
| Value known | Can be at run time | Must be at compile time |
| Use for array sizes | Only if the value is a compile time constant | Yes |
#include <array>
#include <iostream>
constexpr int square(int n) { return n * n; }
int main() {
constexpr int size = square(3); // calculated while compiling
std::array<int, size> a{};
const int input = 5; // const, set at the start
std::cout << a.size() << ' ' << input << '\n';
}
Output
9 5
See C++ Variables.
Learn more about the similar topics:
| Tutorials |
|---|
| C++ Variables |
| C++ Data Types |
| C++ Type Conversion and Casting |
| C++ Operators |
| Exercises & Assignments |
|---|
| Print your name and age with variables |
| Convert Celsius to Fahrenheit |
| Interview Questions & Answers |
|---|
| What is the auto keyword in C++? |
| What is the difference between const and constexpr in C++? |