What are the rules that govern the uninitialized bytes of a union ? (Assuming some are initialized)
Below is a 32 bytes union of which I initialize only the first 16 bytes via the first member. It seems the remaining bytes are zero-initialized. That's great for my use case but I am wondering what's the rule behind this - I was expecting garbage.
#include <cstdint>
#include <iostream>
using namespace std;
union Blah {
struct {
int64_t a;
int64_t b;
};
int64_t c[4];
}
int main()
{
Blah b = {{ 1, 2 }}; // initialize first member, so only the first 16 bytes.
// prints 1, 2, 0, 0 -- not 1, 2, <garbage>, <garbage>
cout << b.c[0] << ", " << b.c[1] << ", " << b.c[2] << ", " << b.c[3] << '\n';
return 0;
}
I've compiled on GCC 4.7.2 with -O3
-Wall
-Wextra
-pedantic
(that last one required giving a name to the anonymous struct). That hopefully should save me from being lucky.
I've also tried to overlay two variables with two different scopes on the stack but gcc didn't give them the same address.
I've also tried replacing the array by another struct in that case that would have mattered, but it didn't change anything.
I can't access online compilers from here, they're blocked by my work.