Difference between `constexpr` and `const`

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

    A const int var can be dynamically set to a value at runtime and once it is set to that value, it can no longer be changed.

    A constexpr int var cannot be dynamically set at runtime, but rather, at compile time. And once it is set to that value, it can no longer be changed.

    Here is a solid example:

    int main(int argc, char*argv[]) {
        const int p = argc; 
        // p = 69; // cannot change p because it is a const
        // constexpr int q = argc; // cannot be, bcoz argc cannot be computed at compile time 
        constexpr int r = 2^3; // this works!
        // r = 42; // same as const too, it cannot be changed
    }
    

    The snippet above compiles fine and I have commented out those that cause it to error.

    The key notions here to take note of, are the notions of compile time and run time. New innovations have been introduced into C++ intended to as much as possible ** know ** certain things at compilation time to improve performance at runtime.

    Any attempt of explanation which does not involve the two key notions above, is hallucination.

提交回复
热议问题