Difference between `constexpr` and `const`

后端 未结 9 1470
无人共我
无人共我 2020-11-22 03:48

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
9条回答
  •  长情又很酷
    2020-11-22 04:34

    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
    

提交回复
热议问题