https://gcc.gnu.org/bugzilla/show_bug.cgi?id=111436
Bug ID: 111436 Summary: Wrong code when bit-casting struct through pointer Product: gcc Version: 12.3.1 Status: UNCONFIRMED Severity: normal Priority: P3 Component: c++ Assignee: unassigned at gcc dot gnu.org Reporter: josopait at goopax dot com Target Milestone: --- Does gcc produce wrong code here? The program below is part of a bitwise conversion mechanism, similar to std::bit_cast, but for more general types. The output should be: from=17,23 to=17,23 But with -O2 or higher the output is: from=17,23 to=0,0 I tried with gcc 12, 13, and 14 on x86_64 linux. #include <iostream> #include <cstdint> #include <array> using namespace std; template<typename TO, typename FROM> inline void reinterpret_switch3(TO& to, const FROM& from) { to = *reinterpret_cast<const TO*>(&from); } template<typename TO, typename FROM> inline void reinterpret_switch2(TO& to, const FROM& from) { reinterpret_switch3(to, array<FROM, 1>({ { from } })); } template<typename TO, typename FROM> inline void reinterpret_switch(TO& to, const FROM& from) { array<TO, 1> tmp; reinterpret_switch2(tmp, from); to = tmp[0]; } int main(int argc, char** argv) { pair<uint32_t, uint32_t> from = {17, 23}; pair<int32_t, int32_t> to; reinterpret_switch(to, from); cout << "from=" << from.first << "," << from.second << endl; cout << "to=" << to.first << "," << to.second << endl; }