26

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.

3
  • You mean on functions, or variables, or both?
    – aschepler
    Aug 10, 2016 at 17:03
  • 10
    For the record, I disagree with the close-vote. The question is asking for a technical reason why this can't be done, and the existing answer gives just such an answer--without any opinion involved. Aug 10, 2016 at 17:11
  • Related: stackoverflow.com/q/14472359/5740428 (not a duplicate, because the linked question is about language design; this one is about language implementation) Sep 4 at 9:39

3 Answers 3

19

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.

10
  • 1
    It's probably also worth noting that even constexpr doesn't guarantee compile-time evaluation except when evaluated in a compile-time context (such as a template argument), although that's not explicitly part of the question. Aug 10, 2016 at 17:09
  • @KyleStrand: You're correct that the Standard requires the compiler to detect that the expression used to initialize a constexpr object is precomputable (according to the rules laid out in the Standard), not always to actually do it.
    – Ben Voigt
    Aug 10, 2016 at 17:10
  • 3
    I just mention this because one can easily imagine incorrect answers to the original question based on the mistaken idea that constexpr forces compile-time evaluation. Aug 10, 2016 at 17:12
  • This answer is a pretty good one. It's in two parts. The first part claims that requiring constexpr provides a useful diagnostic ability. I'm not sold on this especially given the convenience of not having to explicitly apply the keyword constexpr. Aug 11, 2016 at 16:01
  • @RobertRamey: The very first part tells you that good compilers will optimze and precompute at compile-time in many cases even when constexpr is not specified. That's your "convenience". The keyword gives you the diagnostic, plus the ability to use the result in places where a compile-time constant is required -- and in those places implicit optimizations will never get you there because they don't yield a compile-time constant expression.
    – Ben Voigt
    Aug 11, 2016 at 16:08
12

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.

7
  • This is the first useful answer so far. I would paraphrase your response by saying that, for a particular function, whether or not it could be evaluated at compile time would be dependent on the implementation which is outside the requirements specified by the standard. So switching standard library implementations could break a program. Dec 30, 2017 at 17:49
  • On the other hand, all functions which can be constexpr share certain characteristics - no side effects, depend only on function arguments, etc. This information is available in the specification of the function interface which is defined in the standard for all standard library functions. Soooo - I don't think making all functions that can be constexpr actually be constexpr would be a problem. I would add that the constexpr keyword would still have a role in enforcing that the function implementation actually be constexpr and produce a syntax error if it isn't. Dec 30, 2017 at 17:56
  • re: paraphrase: yep, you got it now; re: first useful answer: glad to hear it. I actually just took mattnewport's last few comments and made explicit all the stuff that he was trying to imply by the word "portable"; re: "I don't think making all functions that can be constexpr actually be constexpr would be a problem": way too aggressive I think. Consider, for instance, the trig functions. Their specification probably meets the requirements. (I didn't check.) But I doubt most implementations meet them. Do you want to insist everyone rewrite their trig functions?
    – Mark VY
    Jan 1, 2018 at 7:22
  • Consider, for instance, the trig functions ... I would be very surprised if any trig function depended on having side effects or depended on anything other than it's arguments. So I would suspect the correctness of any trig function which would fail to compile if made constexpr. Jan 2, 2018 at 12:13
  • But suppose I'm wrong and suppose some particular implementation of some particular trig function would not be automatically constexpr. Things would be no different than they are now. No currently functioning program would break. Jan 2, 2018 at 12:16
1

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.

13
  • "I'm not sure how you could specify this portably ..." easy - the same way that the compiler currently determines whether constexpr is used correctly. The diagnostics are already implemented. But the are only applied to expressions marked as constexpr. I propose to apply them to any expression invoked at compile time. That's all. Aug 12, 2016 at 19:06
  • 1
    @RobertRamey I think you missed the point I was making: you couldn't portably rely on any given standard library function being constexpr even if it happened to be in a particular implementation without it being documented as guaranteed to be so which would require just the same time consuming discussion that is happening anyway to mark them constexpr Aug 14, 2016 at 4:13
  • 1
    @RobertRamey you're missing my point. For a function in the standard library to be portably usable in a constexpr context, it is not enough for the standard to just say any function that can be compiled constexpr will be. The standard also has to specify which functions are required to be compilable as constexpr. Whether that is specified as now with the keyword constexpr or is just stated in the standard document it still has to be discussed and added to the standard for every function that is decided should be portably constexpr. Aug 14, 2016 at 16:58
  • 1
    @RobertRamey it's true in the context I stated it: "For a function in the standard library to be portably usable in a constexpr context". Under an implicit constexpr rule like you suggest, the standard would still need to state that a function must be constexpr compilable for code to be able to rely on use in a constexpr context being portable. Under the much more restrictive C++11 constexpr rules that was more of a problem than in C++14 but there are still reasonable implementations that would be problematic (like using a lambda, at least until we get constexpr lambdas). Aug 15, 2016 at 23:54
  • 2
    @RobertRamey I'm not sure why you're not getting the point I'm making. I'll try another example. In C++11 std::max() was not constexpr and under C++11 constexpr rules there could be valid implementations (using an if statement) that would not be compilable as constexpr. As a user, having implicit constexpr would not be enough to use the result of std::max() portably as say an array size because it might happen to compile on one implementation but could fail on another compliant implementation. The standard would still need to be updated to say max() should be constexpr friendly. Aug 16, 2016 at 16:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.