inline vs. constexpr?

Asserting that something can be computed at compile-time is a pretty strong kind of optimization.

Inlining merely removes a function call, by copy/pasting the function body into the call site. The function body still has to be executed, you just save the overhead of a function call.

But if you make the same code be evaluated at compile-time, it is free at runtime.

But neither inline nor constexpr are primarily about optimization. inline‘s main purpose is to suppress the one-definition-rule, so that functions can be defined in headers (which is useful for templates, and incidentally, also makes the inlining optimization easier)

And constexpr is there because it is useful in metaprogramming, and incidentally, it may help the compiler better optimize the code, by moving more computations to compile-time.

Leave a Comment