Sujet : curiosity about constexpr
De : thiago.adams (at) *nospam* gmail.com (Thiago Adams)
Groupes : comp.lang.cDate : 08. Oct 2024, 12:41:18
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <ve35ou$261u1$1@dont-email.me>
User-Agent : Mozilla Thunderbird
While thinking about how to implement constexpr in Cake for structs/unions, a question came to mind.
Do they emulated "shared" storage in unions?
So, I decided to test it using GCC and Clang.
https://godbolt.org/z/dqz9jcx13union X
{
int i;
bool b;
};
constexpr union X x = { .i = 1 };
static_assert(x.i == 1);
static_assert(x.b == 1); //error
The answer seems NO, constexpr don't emulate what happens in runtime.
I also checked in C++.
https://godbolt.org/z/6qosY4xbKunion X {
int i;
bool b;
};
consteval int f(int i)
{
union X x={0};
x.i = i;
return x.b;
}
int main()
{
constexpr int i = f(2);
}