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 |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |