ProDeveloperTutorial.com

Tutorials and Programming Solutions
Menu
  • Shell Scripting
  • System Design
  • Linux System Programming
  • 4g LTE
  • Coding questions
  • C
  • C++
  • DSA
  • GIT
  • 450 DSA Cracker
  • 5G NR
  • O-RAN

C++ 11 feature: constexpr

prodevelopertutorial February 26, 2020

“constexpr” is a new concept in C++ 11.

In this chapter we shall have a look at “constexpr” topic.

“constexpr” are used in the scenario, where there is a possibility to evaluate the value of the function or variable at compile time.

“constexpr” is the keyword used to create a constant expression.

Constant expression can be used on functions, conditional statements and also in constructors.

But there are some conditions to use them.

Rules for constexpr for variable:

1. The type must be a literal type.
2. The constructor parameters must contain only literal type.

Rules for constexpr for a function:

1. Function sould not be a virtual function.
2. Must return a literal type.
3. “constexpr” function can call another “constexpr” function, but not a normal function.

Example for a simple constexpr function:

#include <iostream>
//for more C++ tutorial visit www.ProDeveloperTutorial.com

using namespace std;

constexpr int add (int a, int b)
{
    return a+b;
}



int main()
{
    int a;
    int b;
    
    cout<<"Enter the values of a and b"<<endl;
    cin>> a >>b;
    
    cout<<add(a,b)<<endl;
    
    cout<<add(10,20)<<endl;
    
    return 0;
}

Output:

Enter the values of a and b
1 2

3
30

As you can see in the above example, the line “cout<<add(10,20)<<endl;”, the result can be known as compile time.

But the value for “cout<<add(a,b)<<endl;”m the value cannot be known at compile time. Because at runtime the user can provide values to a and b.

So this means, when there is a possibility to know the result at compile time, even if the compilation time is more, during runtime the execution is faster.

But only by doing so will not make the program faster. To make sure that the “add(10, 20)” statement is evaluated at compile time, you should store the result at constexpr variable.

i.e If you store it like “constexpr int result = add(10, 20);”. This will make sure that the expression is evaluated at compile time only.

Example for constexpr in if statement

In the below example, we shall check if the size of “int” datatype is greater than 4 or not using “constexpr”

#include <iostream>
//for more C++ tutorial visit www.ProDeveloperTutorial.com

using namespace std;

int main()
{
    if constexpr (sizeof(int) > 4)
    {
        cout<<"Size is greater than 4"<<endl;
    }
    else
    {
        cout<<"Size is lesser than 4"<<endl;
    }
    
    return 0;
}

Output:

Size is lesser than 4

 

Example for constexpr with constructor:

 

#include <iostream>
//for more C++ tutorial visit www.ProDeveloperTutorial.com

using namespace std;


class MyClass 
{ 
    int a, b; 
public:

    // constexpr constructor 
    constexpr MyClass (int num1, int num2) : a(num1), b(num2) {} 
      
    constexpr int getSum ()  {   return (a+b); } 
}; 
  

int main() 
{ 
    // Below object is initialized at compile time 
    constexpr MyClass obj(10, 20); 
    cout << obj.getSum()<<endl; 
    return 0; 
} 

Output:

30

 

 

List Of Tutorials available in this website:

C Programming 20+ ChaptersC++ Programming 80+ Chapters
100+ Solved Coding QuestionsData Structures and Algorithms 85+ Chapters
System design 20+ ChaptersShell Scripting 12 Chapters
4g LTE 60+ ChaptersMost Frequently asked Coding questions
5G NR 50+ ChaptersLinux System Programming 20+ chapters

 

 

 

Share
Email
Tweet
Linkedin
Reddit
Stumble
Pinterest
Prev Article
Next Article

About The Author

prodevelopertutorial

Follow this blog to learn more about C, C++, Linux, Competitive Programming concepts, Data Structures.

One Response

  1. http://www.cplusplus.com/user/cuoihoivietnam/
    Log in to Reply

    Excellent blog you have here but I was wondering if you knew of any user discussion forums that cover the same topics discussed here?
    I’d really like to be a part of community where I can get comments from other knowledgeable individuals that share the same interest.
    If you have any recommendations, please let me know. Thanks a lot!

    March 16, 2020

Leave a Reply Cancel Reply

You must be logged in to post a comment.

ProDeveloperTutorial.com

Tutorials and Programming Solutions
Copyright © 2023 ProDeveloperTutorial.com
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept”, you consent to the use of ALL the cookies.
Do not sell my personal information.
Cookie SettingsAccept
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT