Difference between `constexpr` and `const`

2018-12-31 10:35发布

What's the difference between constexpr and const?

  • When can I use only one of them?
  • When can I use both and how should I choose one?

7条回答
公子世无双
2楼-- · 2018-12-31 10:59

As @0x499602d2 already pointed out, const only ensures that a value cannot be changed after initialization where as constexpr (introduced in C++11) guarantees the variable is a compile time constant.
Consider the following example(from LearnCpp.com):

cout << "Enter your age: ";
int age;
cin >> age;

const int myAge{age};        // works
constexpr int someAge{age};  // error: age can only be resolved at runtime
查看更多
登录 后发表回答