Hacker News new | ask | show | jobs
by robotresearcher 1167 days ago
You're both right, but you're talking about different things.

If you use the same values at run time as you use in the tests, the tests predict the behavior as desired.

If you use different values at run time as you use in the tests, the tests do not predict the behavior as desired.

1 comments

> You're both right, but you're talking about different things.

The GP post is explicitly claiming that the values don't matter, and that per the standard a constexpr function should be guaranteed by the compiler to be incapable of producing UB (or else compilation should fail and it should not be allowed to be declared constexpr). This is simply false. Here is the GP statement:

>> That is, conditional constepxr code that depends on values and could produce UB is not valid constexpr code, and a compiler is not supposed to compile it. [emphasis mine]

> If you use the same values at run time as you use in the tests, the tests predict the behavior as desired.

Even this is not fully guaranteed by the standard, as core constant expressions must only be guaranteed not to invoke core language UB. They may still be considered core constant expressions and evaluated at compile time even if they exhibit standard library UB (e.g. if they are not respecting some preconditions of an std::vector method).

"The GP post is explicitly claiming that the values don't matter, and that per the standard a constexpr function should be guaranteed by the compiler to be incapable of producing UB (or else compilation should fail and it should not be allowed to be declared constexpr).

They are so guaranteed - as i cited to you, your example of foo, as used in foo(100), is considered not a constant. There is no such thing as a constexpr expression that can produce UB.

If it can produce UB, it is not constexpr.

That does not mean it will not be validly usable in non-constant contexts! But it is not constexpr.

But foo(1) is a constant expression, and the compiler accepts it.

Not sure what you mean by a "constexpr expression" exactly. My point is that a function can legally be constexpr-qualified even if it can produce UB when called with certain arguments. I think it's very common to call such a function "a constexpr function". Of course, we agree that not every expression where a constexpr function is called is a constant expression (such as foo(100) in my example). However, expressions where that function is called with arguments where it does not produce UB are legal constant expressions (such as foo(1) in my example).

Perhaps I misunderstood your original comment and we are in fact in violent agreement. If so I apologize.