Question on constexpr strictness

Mar 8, 2015 at 6:10am
So I was looking into stuff that can be done with constexpr variables and functions, and the jist I got was that if something is marked as constexpr, the compiler evaluates it and writes its values at compile-time instead of run-time.

Question: Is there an example of a case where something is marked as constexpr but the compiler chooses to not evaluate it at compile time? Or is that not possible?
Mar 8, 2015 at 8:00am
Is there an example of a case where something is marked as constexpr but the compiler chooses to not evaluate it at compile time?
Yes, constexpr function will be evaluated in runtime if at least one argument is not avaliable in compile time:
1
2
3
4
5
6
7
8
9
constexpr int foo(int i)
{ return i; }

//...
constexpr int x = 10;
int y;
std::cin >> y;
constexpr int x1 = foo(x); //foo(x) calculated in compile time, everything works fine
constexpr int y1 = foo(y); //foo(y) cannot be calculated in compile time, line gives you an error as y1 is not initialized with compile-time constant 
Mar 8, 2015 at 4:44pm
Still not quite sure what you mean, how is it possible for that function to be allowed to run at runtime? Like you said, it gives a compiler error on your line 9, and that's what I agree should happen. Can you give an example where it would compile but still be evaluated at run-time?

I'm just trying to figure out how strong the guarantee is that if something is marked constexpr, it has to be able to be evaluated at compile-time, or it's a compiler-time error.
Last edited on Mar 8, 2015 at 4:48pm
Mar 8, 2015 at 6:55pm
gives a compiler error on your line 9, and that's what I agree should happen
It gives you an error because you are trying to assign it result to constexpr variable. If you do constexpr int y1 = foo(y); , then it will compile and foo(y) will be evaluated at runtime.
Mar 8, 2015 at 7:26pm
Okay, part of me was hoping that it would be stricter, but I guess it makes sense from an implementation standpoint.

One more thing, just to be clear: For your example, once you get rid of the constexpr in y1, is x1 (and therefore foo(x) ) still able to be evaluated at compile-time even though y1 is now unable to?
Last edited on Mar 8, 2015 at 7:30pm
Mar 8, 2015 at 7:41pm
Yes, foo(x) will be evaluated in compile time. constexpr functions are guaranteed to be evaluated at compile time if all arguments are compile time constants.

You can use templates to guarantee compile-time evaluation.
Mar 8, 2015 at 8:05pm
Thank you MiiNiPaa, all is clear now.
Topic archived. No new replies allowed.