Announcement

Collapse
No announcement yet.

const vs constexpr.

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    const vs constexpr.

    When to use const and when to use constexpr? What's the difference between them?

    #2
    I believe constexpr is initialized during compile time, so it can be used in situations where a compile time constant is needed. Const can be initialized during compile time or runtime.

    http://stackoverflow.com/questions/1...r-on-variables
    http://stackoverflow.com/questions/1...expr-and-const

    Comment


      #3
      A good way to figure that out is to try to set a static array's size using a variable declared as const or constexpr. A const is a constant expression provided that it is initialized with a constant expression, an integer literal for instance. The problem with const is that it can be initialized at run-time and won't warn you if you assign it to any function that isn't a constant expression, what I mean by that is

      Code:
          const int i = ceil(1024);
          int Array[i] = {1,2,2,3,3,4,4};
      Here you'll only get an error because i is being set as the array's size. Whereas if a constexpr was used, it would complain right at the initialization phase. One thing to note however is that a function can also be executed at compile-time so long as its declared constexpr, but there are rules - your compiler should give you a warning if the function will be executed at compile time.

      Code:
      template<typename T>
      constexpr T Max(T a, T b)
      {
          return a < b ? b : a;
      }
      
      int main()
      {
          int a = 1, b = 2;
          Max(a, b);
      }
      For instance in the case above, Max ought to be executed at run-time, the two local variables are passed to registers and pushed on the stack then the call to Max<int> follows. On the other hand if you'd have passed 1 and 2.

      Code:
      template<typename T>
      constexpr T Max(T a, T b)
      {
          return a < b ? b : a;
      }
      
      int main()
      {
          int a = 1, b = 2;
          Max(1,2);
      }
      and check the dissassembly output, then you probably wouldn't have seen much, and the function should be executed at compile-time.

      Comment

      Working...
      X