What is the difference between const and constexpr in C++?

Pointconstconstexpr
MeaningRead only after the startComputed at compile time
Value knownCan be at run timeMust be at compile time
Use for array sizesOnly if the value is a compile time constantYes
#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.