Constexpr function in CPP

Today we gain depth knowledge of a CPP Function that is  Constexpr, with Help of a Program and Their Syntax.

Use constexpr function in CPP

Why use constexpr function in CPP with Example constexpr is instruction(feature) for the compiler to improve the performance of the program by doing computations at compile time instead of at the run time. Where you can use…

Syntax or Example:-

constexpr int addition(int x, int y)
{
return (x + y);
}

int main()
{
const int x = addition(10, 20);
cout << x;
return 0;
}

for example, constexpr in front of function will tell the compiler to evaluate this function at compile-time instead of at the run time, hence it will improve the performance,

It is like before the execution of your program the “const int x” will have the value 30

Q. But if the value is the user given then how compiler calculate the value?

Ans:- it can be applied to variables: A compiler error is raised when any code attempts to modify the value. Unlike const, constexpr can also be applied to functions and class constructors. constexpr indicates that the value, or return value, is constant and, where possible, is computed at compile time.

Q. Also constexpr can be used for array index, which should be at compile time.

Ans.

one thing: there is no guarantee that it will evaluate the value at compile-time, if u pass user-defined values then it will be evaluated at run time even though u have used constexpr for function.

Example of constexpr program

#include <iostream>

using namespace std;

constexpr int addition(int x, int y)
{
return (x + y);
}

int main()
{
int a,b;
cin>>a>>b;
const int x = addition(a, b); // this will evaluate at run time as the value of a and b is not unknown at compile time
cout << x;
return 0;
}

Working principle of Constexpr keyword in CPP

constexpr function in CPP
constexpr function in CPP

Here output of the Program. You need to enter any two Integer Data For adding the two Numbers.

56  // int Value

22  // int Value

78 //  Return Value

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.