### Qualified's blog

By Qualified, history, 4 weeks ago, ,

What are the pros for defining a function to be constexpr. For example the gcd function

ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a; }


can be written using constexpr

constexpr ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a; }


Is there any improvement in time it takes to run or execute the program or any other benefits?

• +5

 » 4 weeks ago, # |   +30 tl;dr no unless args are constexprI've just googled constexpr function c++ cppreference(very good, recommend to use, superior to cplusplus.com) says: The constexpr specifier declares that it is possible to evaluate the value of the function or variable at compile time.So, if you call this function with non constexpr arguments, you will see no improvement, which I verified using costum invocation feature of CF. However you might wanna do some stuff crazy like this.Now I'd like to ask for upvotes
•  » » 4 weeks ago, # ^ |   0 So if I have that gcd function, will it be reasonable to have constexpr in front of it like constexpr ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a; } 
•  » » » 4 weeks ago, # ^ |   0 As I have said it's just extra characters in most cases.
 » 4 weeks ago, # | ← Rev. 2 →   0 A function that is marked constexpr and satisfy some restrictions imposed by the C++ standard will be computed at compile-time if the arguments are all compile time constant expressions. constexpr has no effect on function calls with non-compile time constant arguments.