According to cppreference and Purpose of Unions in C and C++, the code below is UB:
// convert char[8] to uint64_t
uint64_t convert(char c[8]) {
union{
uint64_t v;
char c[8];
} u;
for(int i = 0; i < 8; i++) {
u.c[i] = c[i];
}
return u.v;
}
// another example
union U {
uint64_t v;
struct{
uint32_t l;
uint32_t h;
}d;
};
uint64_t setlow(uint64_t v, uint32_t l) {
U u{v};
u.d.l = l;
return u.v;
}
However, even though it's UB, this kind of usage gives much convenience and I find it actually works for most compilers(GCC/Clang). So I want to know is there any compiler/implementation in practice that will make the code above break?