Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • C++ Data Types
  • C++ Input/Output
  • C++ Arrays
  • C++ Pointers
  • C++ OOPs
  • C++ STL
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ MCQ
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
Open In App
Next Article:
Understanding constexpr Specifier in C++
Next article icon

Understanding constexpr Specifier in C++

Last Updated : 23 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 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 functions not simple functions.
  4. The function should not be of a void type.
  5.  In C++11, prefix increment (++v) was not allowed in constexpr function but this restriction has been removed in C++14.

It might seem like unnecessary to write a function that just returns the multiplication of a given number as constexpr. Other than performance improvement where could this feature be useful?

  • The main advantage of this feature is that it allows us to use a function to evaluate compile-time constant. With this, we could calculate the size of the array at compile time which was not possible before.
C++
// C++ program to demonstrate constexpr function to evaluate // the size of array at compile time. #include <iostream>  constexpr int product(int x, int y) { return (x * y); }  int main() {     int arr[product(2, 3)] = {1, 2, 3, 4, 5, 6};     std::cout << arr[5];     return 0; } 

Output
6
  • Another practical use case is to convert the unit from one system to another. E.g., trigonometric function in C/C++ takes angle in radian whereas most of the people finds easier to use angle in degree. So, we could write ConvertDegreeToRadian() function as constexpr without compromising with performance and readability of the code.
C++
#include <iostream> using namespace std; const double PI = 3.14159265359; constexpr double ConvertDegreeToRadian(const double& dDegree) {     return (dDegree * (PI / 180)); }  int main()  {     auto dAngleInRadian = ConvertDegreeToRadian(90.0);     cout << "Angle in radian: " << dAngleInRadian;     return 0; } 

Output
Angle in radian: 1.5708

 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>    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);      std::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,   constexpr 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 <iostream>   // 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() const { return _h * _w; }  };   // driver program to test function  int main()  {      // Below object is initialized at compile time      constexpr Rectangle obj(10, 20);      std::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. 


Next Article
Understanding constexpr Specifier in C++

K

kartik
Improve
Article Tags :
  • C Language
  • C++
  • CPP-Library
Practice Tags :
  • CPP

Similar Reads

    Understanding nullptr in C++
    Consider the following C++ program that shows problem with NULL (need of nullptr) CPP // C++ program to demonstrate problem with NULL #include <bits/stdc++.h> using namespace std; // function with integer argument void fun(int N) { cout << "fun(int)"; return;} // Overloaded fun
    3 min read
    constinit Specifier in C++ 20
    The constinit specifier is a new feature that is introduced in C++ 20 that allows us to declare a variable with static storage duration. In this article we will discuss the constinit specifier, its usage, advantages, and limitations. What is constinit Specifier? The constinit specifier is used to ma
    3 min read
    if constexpr in C++ 17
    In C++17, if constexpr feature was introduced to allow compile-time branching based on constant expressions. Unlike regular if statements, which are evaluated at runtime, the if constexpr allows the compiler to discard branches of code that do not apply. It means only the branch of code for which th
    3 min read
    Passing Pointers to Functions In C++
    Prerequisites: Pointers in C++Functions in C++ Passing Pointers to functions means declaring the function parameter as a pointer, at the function calling passing the address of the variable and that address will be stored by a parameter that is declared as a pointer. To change the value of any varia
    4 min read
    Return by reference in C++ with Examples
    Pointers and References in C++ held close relation with one another. The major difference is that the pointers can be operated on like adding values whereas references are just an alias for another variable. Functions in C++ can return a reference as it's returns a pointer.When function returns a re
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences