Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why constexpr is not the default for all function? [duplicate]

After relaxing the rules for the constexpr it seems as these functions can be used everywhere. They can be called on both constant (constexpr) and local (mutable) variables as well. So for me it seem as just a hint for the compiler (like inline). I just keep writing it everywhere and remove it if compiler complains. So compiler seems to know everything if a function can be evaluated at compile time or not. Why is it not the default behavior and why do i have to mark anything as constexpr ?

like image 534
Gzp Avatar asked Feb 10 '16 07:02

Gzp


People also ask

Why constexpr instead of define?

#define directives create macro substitution, while constexpr variables are special type of variables. They literally have nothing in common beside the fact that before constexpr (or even const ) variables were available, macros were sometimes used when currently constexpr variable can be used.

Is constexpr guaranteed?

A constexpr function that is eligible to be evaluated at compile-time will only be evaluated at compile-time if the return value is used where a constant expression is required. Otherwise, compile-time evaluation is not guaranteed.

Is constexpr implicitly static?

constexpr is a compile time feature, where inline/static are runtime features. The meaning of constexpr is more restricted than static. The meaning is that given a particular input value the return value is always the same, and the copiler ought to be able to work it out completely during compilation.


2 Answers

constexpr is an interface guarantee. It means that you can use the function in constant expressions.

Once people can use them in constant expressions, they will. But what if you didn't mean for your function to be used that way? What if you previously had a simple implementation that happened to be constexpr-possible, but in a later revision you need to change that (e.g. because you now need to add log output)?

If you remove the constexpr marker, the usage in constant expressions stops compiling, when it worked before, and the users of your function will be upset. Better to not make the function constexpr in the first place, allowing you more freedom to change it later.

But if the compiler automatically makes your function constexpr, you don't have that choice.

like image 120
Sebastian Redl Avatar answered Oct 06 '22 00:10

Sebastian Redl


As pointed here, it makes difference to use function template specialization, defined with constexpr specifier or not in (e.g.) SFINAE context:

The addition of constexpr is causing function templates to be instantiated in unevaluated contexts that otherwise would not.

So, sometimes it would be an undesired behaviour to have all the functions implicitly defined as constexpr.

like image 28
Tomilov Anatoliy Avatar answered Oct 06 '22 00:10

Tomilov Anatoliy