Difference between `constexpr` and `const`

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

    const applies for variables, and prevents them from being modified in your code.

    constexpr tells the compiler that this expression results in a compile time constant value, so it can be used in places like array lengths, assigning to const variables, etc. The link given by Oli has a lot of excellent examples.

    Basically they are 2 different concepts altogether, and can (and should) be used together.

提交回复
热议问题