-2

So I understand that the use of constexpr in C++ is for defined expressions that are be evaluated at compile time, and more obviously to declare a variable or function as a constant expression. My confusion comes from understanding any benefits of using it for simple functions that will not change.

Suppose you have a function to simply square a value...

int square(int x) {
    return x * x;
}

Typically that will never change, or be overridden, however, I've seen people say that it would be better practice to instead define it as...

constexpr int square(int x) {
    return x * x;
}

To me, this seems like such a trivial change. Can anyone enlighten me on serious advantages of declaring such simple expressions as constexpr?

m_callens
  • 6,100
  • 8
  • 32
  • 54

1 Answers1

1

The advantage of that change is that whenever x is known at compile time, result of square could be used to initialize constexpr variables or as a template argument.

SergeyA
  • 61,605
  • 5
  • 78
  • 137