7

With a constexpr-specified function foo_constexpr I have code such as shown below:

const auto x = foo_constexpr(y); static_assert(x==0); 

Under which circumstances could the code then fail to compile, when the declaration of x is changed to constexpr? (After all, x must already be a constant expression for use in the static_assert.) That is:

constexpr auto x = foo_constexpr(y); static_assert(x==0); 
3
  • 1
    What about y? Even if the function is constexpr it can still be called at runtime with a runtime value. Commented Aug 27, 2019 at 7:26
  • Yes, but foo_constexpr can still be part of a constant expression in that case: as long as it doesn't use the value of y when calculating the result. Commented Aug 27, 2019 at 10:34
  • The point of the comment was that in order to give a precise answer you need to specify what y is and how it's used. Commented Aug 27, 2019 at 10:38

1 Answer 1

8

In general, it can fail to compile when the execution of foo_constexpr violates a requirement of constant expressions. Remember, a constexpr function is not a function that is always a constant expression. But rather it is a function that can produce a constant expression for at lease one input! That's it.

So if we were to write this perfectly legal function:

constexpr int foo_constexpr(int y) { return y < 10 ? 2*y : std::rand(); } 

Then we'll get:

constexpr int y = 10; const auto x1 = foo_constexpr(y); // valid, execution time constant constexpr auto x2 = foo_constexpr(y); // invalid, calls std::rand 

But of course, if x is already usable in a constant expression (such as a static assertion), changing to constexpr cannot cause a failure to occur.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. I have it that it does fail when I change to constexpr. Alas I've not yet been able to reduce the code to something useful to share.
@user2023370 - Reducing it would help. But if your use case really involves static_assert and just switching const to constexpr causes failure, then there's potential from something fishy here.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.