constexpr : use, meaning and importance | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

constexpr : use, meaning and importance

Hi I read that constexpr is evaluated at compile time. So does const do. If so , what is the purpose of addition of constexpr in C++? Is it so we can use both interchangeably?

29th May 2020, 6:11 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
6 Answers
+ 2
This in turn can drastically improve runtime performance Consider a Square_root function: (For simplicity am going to use the standard library sqrt function(since it is also a constexpr) for my definition of Square_root) We can define it in two ways: constexpr double Square_root(const double n){return sqrt(n);} And double Square_root (const double n){return sqrt(n);} int main(){ Square_root(9980001);return 0;} You should probably write the two programs in two different sources files and note the corresponding runtime for each What you'll realise is the program with the constexpr function incurs a significantly shorter runtime but slightly longer compile time in comparison to the non-constexpr version since the compiler evaluated it and came up with a value that it then hard-wired into the program.
29th May 2020, 1:28 PM
Anthony Maina
Anthony Maina - avatar
+ 1
For the most part const and constexpr can be used interchangeably.This is especially true for variables
29th May 2020, 1:17 PM
Anthony Maina
Anthony Maina - avatar
+ 1
The real importance of constexpr(at least as far as I know) is in the use of it with functions.
29th May 2020, 1:18 PM
Anthony Maina
Anthony Maina - avatar
+ 1
When applied to functions,it instructs a compiler to evaluate a particular function at compile time if all the values it uses are known and subsequently produce a value
29th May 2020, 1:20 PM
Anthony Maina
Anthony Maina - avatar
+ 1
Generally we don't use sqrt function as it is already in standard library. I understand that you have given a example and I got concept also.... But on the other hand I feel that something which can be evaluated at compile time is not dependent on user input... So, rather than using constexpr , one can directly evaluate value and use as const. Is it okay or some interesting fact I am missing ln this ?
31st May 2020, 5:16 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 1
Think of it this way,.....constexpr functions are mainly used for compile time evaluation,that is,if all arguments of a function are known at compile time and are immutable,then there is no need of generating a normal function to be executed at runtime.Rather,it instructs the to compiler "execute" it and produce a value and in the process,reduce the runtime of the program produced
31st May 2020, 5:42 PM
Anthony Maina
Anthony Maina - avatar