What is the difference between constexpr and const in C++?
Hi everyone! I started learning C++11 and came across the new keyword `constexpr`. Previously I always used `const` to declare immutable variables. But now there's also `constexpr`, and I can't fully understand when to use which.
For example, I write this code:
```cpp
const int size = 5;
int arr[size]; // This works
```
But if I write:
```cpp
int get_size() { return 5; }
const int size = get_size();
int arr[size]; // Compilation error in older standards!
```
I understand that `const` simply prevents modifying the variable after initialization, but doesn't guarantee the value is known at compile time. At the same time, I see examples with `constexpr`:
```cpp
constexpr int square(int x) { return x * x; }
constexpr int val = square(5); // Ok, computed at
No answers yet.
Log in to leave an answer