Qualified's blog

By Qualified, history, 4 weeks ago, In English,

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?

 
 
 
 
  • Vote: I like it
  • +5
  • Vote: I do not like it

»
4 weeks ago, # |
  Vote: I like it +30 Vote: I do not like it

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

  • »
    »
    4 weeks ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    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, # ^ |
        Vote: I like it 0 Vote: I do not like it

      As I have said it's just extra characters in most cases.

»
4 weeks ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

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.