What is the difference between constexpr and const in C++?
Hello! I recently started learning C++11 and came across the `constexpr` keyword. I understand that `const` means the value of a variable cannot be changed after initialization. But `constexpr` also seems to make a variable constant. What's the difference then?
For example, I can write:
```cpp
const int x = 5;
constexpr int y = 5;
```
Both work. But I've heard that `constexpr` can be used with functions. I tried:
```cpp
constexpr int square(int n) {
return n * n;
}
int main() {
const int a = square(5); // Works?
constexpr int b = square(5); // Also works?
int arr[ square(3) ]; // Is this possible?
}
```
This compiles, but I don't understand the real advantage. When should I use `constexpr` instead of `const`? And p
No answers yet.
Log in to leave an answer