constexpr specifier | C++

/constexpr specifier | C++

The constexpr specifier declares that it is possible to evaluate the value of the function or variable at compile time. The main idea is performance improvement of programs by doing computations at compile time rather than run time. constexpr specifies that the value of an object or a function can be evaluated at compile time and the expression can be used in other constant expressions.

// constexpr function for product of two numbers. By specifying constexpr, 
// we suggest compiler to to evaluate value at compiler time 
constexpr int product(int x, int y) 
{ 
  return (x * y); 
} 

int main() 
{ 
  const int x = product(10, 20); 
  return 0; 
}

 

constexpr vs const

  • constexpr is mainly for optimization while const is for practically const objects like value of Pi.
  • Both of them can be applied to member methods. Member methods are made const to make sure that there are no accidental changes by the method. On the other hand, the idea of using constexpr is to compute expressions at compile time so that time can be saved when code is run.
  • const can only be used with non-static member function whereas constexpr can be used with member and non-member functions, even with constructors but with condition that argument and return type must be of literal types.

 

September 11th, 2019|Categories: Programming|Tags: |
avatar
  Subscribe  
Notify of