Difference between `constexpr` and `const`

后端 未结 9 1610
无人共我
无人共我 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:16

    First of all, both are qualifiers in c++. A variable declared const must be initialized and cannot be changed in the future. Hence generally a variable declared as a const will have a value even before compiling.

    But, for constexpr it is a bit different.

    For constexpr, you can give an expression that could be evaluated during the compilation of the program.

    Obviously, the variable declared as constexper cannot be changed in the future just like const.

提交回复
热议问题