Блог пользователя Qualified

Автор Qualified, история, 4 года назад, По-английски

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 года назад, # |
  Проголосовать: нравится +30 Проголосовать: не нравится

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 года назад, # ^ |
      Проголосовать: нравится 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 года назад, # |
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.