A colleague of mine showed me this shocking C++20 program:
#include <iostream>
constexpr int p(auto) { return 0; }
constexpr int q() { return p(0); }
constexpr int p(auto) requires true { return 1; }
static_assert(p(0) == 1);
static_assert(q() == 0);
int main()
{
std::cout << q() << p(0) << '\n';
}
GCC cannot build it due to the error:
Error: symbol `_Z1pIiEiT_' is already defined
Clang builds the program successfully and prints 11( https://gcc.godbolt.org/z/1Gf5vj5oo ). So static_assert(q() == 0) was successfully checked, but std::cout << q() still printed 1. How can this be?
Visual Studio 2019 16.10.4 behaves even more weirdly. In Release configuration it prints also 11, and in Debug configuration it prints 00. And here in both cases run-time values of functions differ from their compile-time values, verified by static_assert.
The only explanation I can think of is that all these are compiler bugs, and a constexpr function must always produce the same result at compile- and run-time. Is that right?
static_asserts prove, why it cannot use the same values in run time?