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?
tl;dr no unless args are constexpr
I'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
So if I have that gcd function, will it be reasonable to have
constexpr
in front of it likeAs I have said it's just extra characters in most cases.
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.