const vs constexpr for variables in C++: what's the difference and which to choose?
Hello everyone! I'm learning C++11/14 and I'm confused about the difference between `const` and `constexpr` when declaring variables. I understand that both keywords make a variable immutable, but everywhere it's written that they are not the same thing.
Here's an example that confuses me:
```cpp
const int x = 42; // Option 1
constexpr int y = 42; // Option 2
const int z = foo(); // Works
constexpr int w = foo(); // Compilation error if foo() is not constexpr
```
I've read that `constexpr` guarantees compile-time evaluation, while `const` does not. But then why is `const` needed if `constexpr` is stricter? And why do I see widespread use of `const` in real projects for variables that are clearly known at compile time?
Another question: if I write `const int size = 10;` and
No answers yet.
Log in to leave an answer
Blogs