Skip to content
Related Articles

Related Articles

Understanding constexpr Specifier in C++

View Discussion
Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 03 Jun, 2022

constexpr is a feature added in C++ 11. The main idea is a performance improvement of programs by doing computations at compile time rather than run time. Note that once a program is compiled and finalized by the developer, it is run multiple times by users. The idea is to spend time in compilation and save time at run time (similar to template metaprogramming).  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. 

Example:

CPP




// C++ program to demonstrate constexpr function for product
// of two numbers. By specifying constexpr, we suggest
// compiler to to evaluate value at compile time
#include <iostream>
  
constexpr int product(int x, int y) { return (x * y); }
  
int main()
{
    constexpr int x = product(10, 20);
    std::cout << x;
    return 0;
}

Output :

200

A function be declared as constexpr

  1. In C++ 11, a constexpr function should contain only one return statement. C++ 14 allows more than one statement.
  2. constexpr function should refer only to constant global variables.
  3. constexpr function can call only other constexpr function not simple function.
  4. The function should not be of a void type and some operators like prefix increment (++v) are not allowed in constexpr function.

 constexpr vs inline Functions

Constexpr

Inline Functions

It removes the function calls as it evaluates the code/expressions in compile time.It hardly removes any function call as it performs an action on expression in the run time.
It is possible to assess the value of the variable or function at compile time.It is not possible to assess the value of the function or variable at compile time.
It does not imply external linkage.It implies external linkage.

Example of performance improvement by constexpr: 

CPP




// A C++ program to demonstrate the use of constexpr 
#include<iostream> 
using namespace std; 
  
constexpr long int fib(int n) 
    return (n <= 1)? n : fib(n-1) + fib(n-2); 
  
int main () 
    // value of res is computed at compile time. 
    constexpr long int res = fib(30); 
    cout << res; 
    return 0; 

Output:

832040

When the above program is run on GCC, it takes 0.003 seconds (We can measure time using the time command) If we remove const from the below line, then the value of fib(5) is not evaluated at compile-time, because the result of constexpr is not used in a const expression.

Change,
  const long int res = fib(30);  
To,
  long int res = fib(30);

After making the above change, the time taken by the program becomes higher by 0.017 seconds.

constexpr with constructors: A constructor that is declared with a constexpr specifier is a constexpr constructor also constexpr can be used in the making of constructors and objects. A constexpr constructor is implicitly inline.

Restrictions on constructors that can use constexpr:

  • No virtual base class
  • Each parameter should be literal
  • It is not a try block function

Example:

CPP




// C++ program to demonstrate uses 
// of constexpr in constructor 
#include <bits/stdc++.h> 
using namespace std; 
  
// A class with constexpr 
// constructor and function 
class Rectangle 
    int _h, _w; 
public
    // A constexpr constructor 
    constexpr Rectangle (int h, int w) : _h(h), _w(w) {} 
      
    constexpr int getArea () { return _h * _w; } 
}; 
  
// driver program to test function 
int main() 
    // Below object is initialized at compile time 
    constexpr Rectangle obj(10, 20); 
    cout << obj.getArea(); 
    return 0; 

Output :

200

 constexpr vs const 

They serve different purposes. constexpr is mainly for optimization while const is for practically const objects like the 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 in 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 the code is run. const can only be used with non-static member functions 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. 

This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!