Purpose of constexpr - c++

This is more of a philosophical question rather than practical code snippet, but perhaps C++ gurus can enlighten me (and apologies if it's been asked already).
I have been reading Item 15 in Meyers's "Effective Modern C++" book, as well as this thread: implicit constexpr? (plus a reasonable amount of googling). The item goes over usage of constexpr for expressions, namely that it defines functions that can return compile time values given compile time inputs.
Moreover, the StackOverflow thread I referred to shows that some compilers are perfectly capable of figuring out for themselves which function invocation results are known at compile time.
Hence the question: why was constexpr added to the standard as compared to defining when compilers should derive and allow static/compile-time values?
I realise it makes various compile-only (e.g. std::array<T, constexpr>) definitions less predictable, but on the other hand, as per Meyers's book, constexpr is a part of the interface,..., if you remove it, you may cause arbitrarily large amounts of client code to stop compiling.
So, not only having explicit constexpr requires people to remember adding it, it also adds permanent semantics to the interface.
Clarification: This question is not about why constexpr should be used. I appreciate that having an ability to programatically derive compile-time values is very useful, and employed it myself on a number of occasions. It's a question on why it is mandatory in situations where compiler may deduce const-time behaviour on its own.
Clarification no. 2: Here is a code snippet showing that compilers do not deduce that automatically, I've used g++ in this case.
#include <array>
size_t test()
{
return 42;
}
int main()
{
auto i = test();
std::array<int, i> arrayTst;
arrayTst[1] = 20;
return arrayTst[1];
}
std::array declaration fails to compile because I have not defined test() as constexpr, which is of course as per standard. If the standard were different, nothing would have prevented gcc from figuring out independently that test() always returns a constant expression.
This question does not ask "what the standard defines", but rather "why the standard is the way it is"?

Before constexpr the compilers could sometimes figure out a compile time constant and use it. However, the programmer could never know when this would happen.
Afterwards, the programmer is immediately informed if an expression is not a compile time constant and he or she realizes the need to fix it.

Related

c++ why do constexpr functions need to be marked constexpr? [duplicate]

To the best of my knowledge, the inline keyword in c++ can be traced back to old compilers (then known as "optimizing compilers") not being able to optimize as well as modern ones, so marking a function as inline told the compiler that this should be inlined, and as a side effect prevented ODR issues. As compilers got better, someone realized that the compilers can do a much better job of optimizing than the programmer, and so the inline requirement of the compiler became more of a 'hint' that most (all?) modern compilers ignore.
Enter C++11 and subsequent versions. constexpr seems to me to be in a similar situation, at least for some of its uses, specifically functions and variables. As I understand it, it tells the compiler that a certain function may be evaluated at compile time. But that is something the compiler should be able to figure out on its own. Is this feature also going to become a 'hint' once compilers get better at optimizing?
Note: I am not asking about other uses of constexpr, such as with if statements. I understand those are needed.
As I understand it, it tells the compiler that a certain function may be evaluated at compile time.
Not "may", but "can". The constexpr keyword does not tell the compiler what it is allowed to do (it may evaluate anything it wants at compile time). Rather the keyword tells the compiler a desired quality of the variable or function, specifically that it can be used in constant expressions. The compiler will complain (error or warning) if the program fails to live up to that desire. You get a more relevant error message than you would have gotten otherwise – the compiler can tell you why your entity does not qualify for compile-time evaluation since it knows that your intent was for the entity to be a compile-time constant.
For example, if you defined const unsigned a, it is an error to use std::array<int, a> if the value of a is not known at compile time. The error might be in the initialization of a, or it might be that the template parameter was supposed to be b instead of a. The compiler would have to report the error as "a is not a constant expression" and let the programmer investigate. On the other hand, if a was declared constexpr, the compiler would instead complain about the reason the value of a is not known at compile time, leading to less time debugging.
Without constexpr, the following code produces a possibly weak error message.
{
const unsigned a = foo();
const unsigned b = 42;
std::array<int, a> stuff; // Error: 'a' is not a constant expression.
// ...
}
After declaring both a and foo() to be constexpr, the error disappears. Why? Because last week when you wrote foo(), the compiler was told that the function had to be usable in constant expressions. As a result, the compiler pointed out why foo() could not be evaluated at compile time, and you fixed the bug right away. That was last week, while the implementation of foo() was still fresh in your mind. Not this week, after doing a dozen other things, including the hour spent arguing with the compiler because you believed a had to be a constant expression since it was initialized with foo().
An ideal compiler could maybe figure out which functions are actually constexprand in that sense one could view that keyword as a hint to the compiler.
But I think it makes more sense to compare const and constexpr in terms of what they tell the compiler and the human reader. An ideal compiler could also figure out, which variables and member functions should be const. As you probably know, there are other good reasons to mark everything possible const (compiler finds bugs for you, much easier to read, helps the compiler in optimization).
The same is true for constexpr. If you declare a variable constexpr, that cannot be computed at compile time, you get an error, you have documented that the variable can be computed at compile time and it helps the compiler in optimization.
Also note that ignoring constexpr does not make sense for runtime performance, which is not true for inline.
But that is something the compiler should be able to figure out on its
own. Is this feature also going to become a 'hint' once compilers get
better at optimizing?
constexpr is not merely an optimization - without
it, the compiler is not allowed to use a function in contexts where a constant expression is required, e.g. in non-type template arguments.
But I am sure you already know that much. The real question is: should a future C++ standard allow using a function in constant expression context even though it is not explicitly marked constexpr - in case if it satisfies contexpr requirements?
No, I think it is the opposite direction from C++ development. Consider C++20 concept. One of its major goals is to improve error messages: instead of going through nested template definitions, the compiler knows early that the template argument does not meet a requirement. Keyword constexpr serves the same goal: the compiler, instead of going through a function call tree and finding that a function deep in the call stack cannot be evaluated at compile-time, reports the error early.

Is constexpr the new inline?

To the best of my knowledge, the inline keyword in c++ can be traced back to old compilers (then known as "optimizing compilers") not being able to optimize as well as modern ones, so marking a function as inline told the compiler that this should be inlined, and as a side effect prevented ODR issues. As compilers got better, someone realized that the compilers can do a much better job of optimizing than the programmer, and so the inline requirement of the compiler became more of a 'hint' that most (all?) modern compilers ignore.
Enter C++11 and subsequent versions. constexpr seems to me to be in a similar situation, at least for some of its uses, specifically functions and variables. As I understand it, it tells the compiler that a certain function may be evaluated at compile time. But that is something the compiler should be able to figure out on its own. Is this feature also going to become a 'hint' once compilers get better at optimizing?
Note: I am not asking about other uses of constexpr, such as with if statements. I understand those are needed.
As I understand it, it tells the compiler that a certain function may be evaluated at compile time.
Not "may", but "can". The constexpr keyword does not tell the compiler what it is allowed to do (it may evaluate anything it wants at compile time). Rather the keyword tells the compiler a desired quality of the variable or function, specifically that it can be used in constant expressions. The compiler will complain (error or warning) if the program fails to live up to that desire. You get a more relevant error message than you would have gotten otherwise – the compiler can tell you why your entity does not qualify for compile-time evaluation since it knows that your intent was for the entity to be a compile-time constant.
For example, if you defined const unsigned a, it is an error to use std::array<int, a> if the value of a is not known at compile time. The error might be in the initialization of a, or it might be that the template parameter was supposed to be b instead of a. The compiler would have to report the error as "a is not a constant expression" and let the programmer investigate. On the other hand, if a was declared constexpr, the compiler would instead complain about the reason the value of a is not known at compile time, leading to less time debugging.
Without constexpr, the following code produces a possibly weak error message.
{
const unsigned a = foo();
const unsigned b = 42;
std::array<int, a> stuff; // Error: 'a' is not a constant expression.
// ...
}
After declaring both a and foo() to be constexpr, the error disappears. Why? Because last week when you wrote foo(), the compiler was told that the function had to be usable in constant expressions. As a result, the compiler pointed out why foo() could not be evaluated at compile time, and you fixed the bug right away. That was last week, while the implementation of foo() was still fresh in your mind. Not this week, after doing a dozen other things, including the hour spent arguing with the compiler because you believed a had to be a constant expression since it was initialized with foo().
An ideal compiler could maybe figure out which functions are actually constexprand in that sense one could view that keyword as a hint to the compiler.
But I think it makes more sense to compare const and constexpr in terms of what they tell the compiler and the human reader. An ideal compiler could also figure out, which variables and member functions should be const. As you probably know, there are other good reasons to mark everything possible const (compiler finds bugs for you, much easier to read, helps the compiler in optimization).
The same is true for constexpr. If you declare a variable constexpr, that cannot be computed at compile time, you get an error, you have documented that the variable can be computed at compile time and it helps the compiler in optimization.
Also note that ignoring constexpr does not make sense for runtime performance, which is not true for inline.
But that is something the compiler should be able to figure out on its
own. Is this feature also going to become a 'hint' once compilers get
better at optimizing?
constexpr is not merely an optimization - without
it, the compiler is not allowed to use a function in contexts where a constant expression is required, e.g. in non-type template arguments.
But I am sure you already know that much. The real question is: should a future C++ standard allow using a function in constant expression context even though it is not explicitly marked constexpr - in case if it satisfies contexpr requirements?
No, I think it is the opposite direction from C++ development. Consider C++20 concept. One of its major goals is to improve error messages: instead of going through nested template definitions, the compiler knows early that the template argument does not meet a requirement. Keyword constexpr serves the same goal: the compiler, instead of going through a function call tree and finding that a function deep in the call stack cannot be evaluated at compile-time, reports the error early.

What are the advantages of using consteval instead of constexpr function?

I know the difference in requirements, I am mostly interested in what benefits from code quality it brings.
Few things I can think of:
reader can just read the function signature and know that function is evaluated at compile time
compiler may emit less code since consteval fns are never used at runtime(this is speculative, I have no real data on this)
no need to have variables to force ctfe, example at the end
note: if code quality is too vague I understand some people might want to close this question, for me code quality is not really that vague term, but...
example where constexpr failure is delayed to runtime:
constexpr int div_cx(int a, int b)
{
assert(b!=0);
return a/b;
}
int main()
{
static constexpr int result = div_cx(5,0); // compile time error, div by 0
std::cout << result;
std::cout << div_cx(5,0) ; // runtime error :(
}
In order to have meaningful, significant static reflection (reflection at compile time), you need a way to execute code at compile time. The initial static reflection TS proposal used traditional template metaprogramming techniques, because those were the only effective tools for executing code at compile-time at all.
However, as constexpr code gained more features, it became increasingly more feasible to do compile-time static reflection through constexpr functions. One problem with such ideas is that static reflection values cannot be allowed to leak out into non-compile-time code.
We need to be able to write code that must only be executed at compile-time. It's easy enough to do that for small bits of code in the middle of a function; the runtime version of that code simply won't contain the reflection parts, only the results of them.
But what if you want to write a function that takes a reflection value and returns a reflection value? Or a list of reflection values?
That function cannot be constexpr, because a constexpr function must be able to be executed at runtime. You are allowed to do things like get pointers to constexpr functions and call them in ways that the compiler can't trace, thus forcing it to execute at runtime.
A function which takes a reflection value can't do that. It must execute only at compile-time. So constexpr is inappropriate for such functions.
Enter consteval: a function which is "required" to execute only at compile time. There are specific rules in place that make it impossible for pointers to such functions to leak out into runtime code and so forth.
As such, consteval doesn't have much purpose at the moment. It gets used in a few places like source_location::current(), which fundamentally makes no sense to execute at runtime. But ultimately, the feature is a necessary building-block for further compile-time programming tools that don't exist yet.
This was laid down in the paper that originally proposed this feature:
The impetus for the present paper, however, is the work being done by SG7 in the realm of compile-time reflection. There is now general agreement that future language support for reflection should use constexpr functions, but since "reflection functions" typically have to be evaluated at compile time, they will in fact likely be immediate functions.

Why can't constexpr just be the default?

constexpr permits expressions which can be evaluated at compile time to be ... evaluated at compile time.
Why is this keyword even necessary? Why not permit or require that compilers evaluate all expressions at compile time if possible?
The standard library has an uneven application of constexpr which causes a lot of inconvenience. Making constexpr the "default" would address that and likely improve a huge amount of existing code.
It already is permitted to evaluate side-effect-free computations at compile time, under the as-if rule.
What constexpr does is provide guarantees on what data-flow analysis a compliant compiler is required to do to detect1 compile-time-computable expressions, and also allow the programmer to express that intent so that they get a diagnostic if they accidentally do something that cannot be precomputed.
Making constexpr the default would eliminate that very useful diagnostic ability.
1 In general, requiring "evaluate all expressions at compile time if possible" is a non-starter, because detecting the "if possible" requires solving the Halting Problem, and computer scientists know that this is not possible in the general case. So instead a relaxation is used where the outputs are { "Computable at compile-time", "Not computable at compile-time or couldn't decide" }. And the ability of different compilers to decide would depend on how smart their test was, which would make this feature non-portable. constexpr defines the exact test to use. A smarter compiler can still pre-compute even more expressions than the Standard test dictates, but if they fail the test, they can't be marked constexpr.
Note: despite the below, I admit to liking the idea of making constexpr the default. But you asked why it wasn't already done, so to answer that I will simply elaborate on mattnewport's last comment:
Consider the situation today. You're trying to use some function from the standard library in a context that requires a constant expression. It's not marked as constexpr, so you get a compiler error. This seems dumb, since "clearly" the ONLY thing that needs to change for this to work is to add the word constexpr to the definition.
Now consider life in the alternate universe where we adopt your proposal. Your code now compiles, yay! Next year you decide you to add Windows support to whatever project you're working on. How hard can it be? You'll compile using Visual Studio for your Windows users and keep using gcc for everyone else, right?
But the first time you try to compile on Windows, you get a bunch of compiler errors: this function can't be used in a constant expression context. You look at the code of the function in question, and compare it to the version that ships with gcc. It turns out that they are slightly different, and that the version that ships with gcc meets the technical requirements for constexpr by sheer accident, and likewise the one that ships with Visual Studio does not meet those requirements, again by sheer accident. Now what?
No problem you say, I'll submit a bug report to Microsoft: this function should be fixed. They close your bug report: the standard never says this function must be usable in a constant expression, so we can implement however we want. So you submit a bug report to the gcc maintainers: why didn't you warn me I was using non-portable code? And they close it too: how were we supposed to know it's not portable? We can't keep track of how everyone else implements the standard library.
Now what? No one did anything really wrong. Not you, not the gcc folks, nor the Visual Studio folks. Yet you still end up with un-portable code and are not a happy camper at this point. All else being equal, a good language standard will try to make this situation as unlikely as possible.
And even though I used an example of different compilers, it could just as well happen when you try to upgrade to a newer version of the same compiler, or even try to compile with different settings. For example: the function contains an assert statement to ensure it's being called with valid arguments. If you compile with assertions disabled, the assertion "disappears" and the function meets the rules for constexpr; if you enable assertions, then it doesn't meet them. (This is less likely these days now that the rules for constexpr are very generous, but was a bigger issue under the C++11 rules. But in principle the point remains even today.)
Lastly we get to the admittedly minor issue of error messages. In today's world, if I try to do something like stick in a cout statement in constexpr function, I get a nice simple error right away. In your world, we would have the same situation that we have with templates, deep stack-traces all the way to the very bottom of the implementation of output streams. Not fatal, but surely annoying.
This is a year and a half late, but I still hope it helps.
As Ben Voigt points out, compilers are already allowed to evaluate anything at compile time under the as-if rule.
What constexpr also does is lay out clear rules for expressions that can be used in places where a compile time constant is required. That means I can write code like this and know it will be portable:
constexpr int square(int x) { return x * x; }
...
int a[square(4)] = {};
...
Without the keyword and clear rules in the standard I'm not sure how you could specify this portably and provide useful diagnostics on things the programmer intended to be constexpr but don't meet the requirements.

Why is constexpr not automatic? [duplicate]

This question already has answers here:
Why do we need to mark functions as constexpr?
(4 answers)
Closed 2 years ago.
As far as I understand it, constexpr can be seen as a hint to the compiler to check whether given expressions can be evaluated at compile-time and do so if possible.
I know that it also imposes some restriction on the function or initialization declared as constexpr but the final goal is compile-time evaluation, isn't it?
So my question is, why can't we leave that at the compiler? It is obviously capable of checking the pre-conditions, so why doesn't it do for each expression and evaluate at compile-time where possible?
I have two ideas on why this might be the case but I am not yet convinced that they hit the point:
a) It might take too long during compile-time.
b) Since my code can use constexpr functions in locations where normale functions would not be allowed the specifier is also kind of part of the declaration. If the compiler did everything by itself, one could use a function in a C-array definition with one version of the function but with the next version there might be a compiler-error, because the pre-conditions for compile-time evaluation are no more satisfied.
constexpr is not a "hint" to the compiler about anything; constexpr is a requirement. It doesn't require that an expression actually be executed at compile time; it requires that it could.
What constexpr does (for functions) is restrict what you're allowed to put into function definition, so that the compiler can easily execute that code at compile time where possible. It's a contract between you the programmer and the compiler. If your function violates the contract, the compiler will error immediately.
Once the contract is established, you are now able to use these constexpr functions in places where the language requires a compile time constant expression. The compiler can then check the elements of a constant expression to see that all function calls in the expression call constexpr functions; if they don't, again a compiler error results.
Your attempt to make this implicit would result in two problems. First, without an explicit contract as defined by the language, how would I know what I can and cannot do in a constexpr function? How do I know what will make a function not constexpr?
And second, without the contract being in the compiler, via a declaration of my intent to make the function constexpr, how would the compiler be able to verify that my function conforms to that contract? It couldn't; it would have to wait until I use it in a constant expression before I find that it isn't actually a proper constexpr function.
Contracts are best stated explicitly and up-front.
constexpr can be seen as a hint to the compiler to check whether given expressions can be evaluated at compile-time and do so if possible
No, see below
the final goal is compile-time evaluation
No, see below.
so why doesn't it do for each expression and evaluate at compile-time where possible?
Optimizers do things like that, as allowed under the as-if rule.
constexpr is not used to make things faster, it is used to allow usage of the result in context where a runtime-variable expression is illegal.
This is only my evaluation, but I believe your (b) reason is correct (that it forms part of the interface that the compiler can enforce). The interface requirement serves both for the writer of the code and the client of the code.
The writer may intend something to be usable in a compile-time context, but not actually use it in this way. If the writer violates the rules for constexpr, they might not find out until after publication when clients who try to use it constexpr fail. Or, more realistically, the library might use the code in a constexpr sense in version 1, refactor this usage out in version 2, and break constexpr compatibility in version 3 without realizing it. By checking constexpr-compliance, the breakage in version 3 will be caught before deployment.
The interface for the client is more obvious --- an inline function won't silently become constexpr-required because it happened to work and someone used that way.
I don't believe your (a) reason (that it could take too long for the compiler) is applicable because (1) the compiler has to check much of the constexpr constraints anyway when the code is marked, (2) without the annotation, the compiler would only have to do the checking when used in a constexpr way (so most functions wouldn't have to be checked), and (3) IIUC the D programming language actually does allow functions to be compile-time evaluated if they meet requirements without any declaration assistance, so apparently it can be done.
I think I remember watching an early talk by Bjarne Stroustrup where he mentioned that programmers wanted fine grained control on this "dangerous" feature, from which I understand that they don't want things "accidentally" executed at compile time without them knowing. (Even if that sound like a good thing.)
There can be many reasons for that, but the only valid one is ultimatelly compilation speed I think ( (a) in your list ).
It would be too much burden on the compiler to determine for every function if it could be computed at compile time.
This argument is weaker as compilation times in general go down.
Like many other features of C++ what end up happening is that we end up with the "wrong defaults".
So you have to tell when you want constexpr instead of when you don't want constexpr (runtimeexpr); you have to tell when you want const intead of where you want mutable, etc.
Admitedly, you can imagine functions that take an absurd amount of time to run at compile time and that cannot be amortized (with other kind of machine resources) at runtime.
(I am not aware that "time-out" can be a criterion in a compiler for constexpr, but it could be so.)
Or it could be that one is compiling in a system that is always expected to finish compilation in a finite time but an unbounded runtime is admissible (or debuggable).
I know that this question is old, but time has illuminated that it actually makes sense to have constexpr as default:
In C++17, for example, you can declare a lambda constexpr but more importantly they are constexpr by default if they can be so.
https://learn.microsoft.com/en-us/cpp/cpp/lambda-expressions-constexpr
Note that lambda has all the "right" (opposite) defaults, members (captures) are const by default, arguments are templates by default auto, and now these functions are constexpr by default.