From this question one could start to believe that alignment of a union is not less than the largest alignment of it's individual members. But I have a problem with the long long
type in gcc/g++. The full example can be found here, but here are the relevant parts for my question:
union ull {
long long m;
};
struct sll {
long long m;
};
int main() {
#define pr(v) cout << #v ": " << (v) << endl
pr(sizeof(long long));
pr(__alignof__(long long));
pr(sizeof(ull));
pr(__alignof__(ull));
pr(sizeof(sll));
pr(__alignof__(sll));
};
This results in the following output:
sizeof(long long): 8
__alignof__(long long): 8
sizeof(ull): 8
__alignof__(ull): 4
sizeof(sll): 8
__alignof__(sll): 4
Why is the alignment of a union member bigger than that of the containing union?
[UPDATE]
According to Keith's answer alignof is wrong here. But I test the following and it seems that alignof tells us the true. See:
union ull {
long long m;
};
long long a;
char b;
long long c;
char d;
ull e;
int main() {
#define pr(v) cout << #v ": " << (v) << endl
pr(size_t((void*)&b));
pr(size_t((void*)&c));
pr(size_t((void*)&d));
pr(size_t((void*)&e));
pr(size_t((void*)&c) - size_t((void*)&b));
pr(size_t((void*)&e) - size_t((void*)&d));
};
The output:
size_t((void*)&b): 134523840
size_t((void*)&c): 134523848
size_t((void*)&d): 134523856
size_t((void*)&e): 134523860
size_t((void*)&c) - size_t((void*)&b): 8
size_t((void*)&e) - size_t((void*)&d): 4
So, the alignment of long long
is 8 and alignment of union containing long long
is 4 in global data. For local scope I cannot test this since it seems that compiler is free to rearrange local data - so this trick does not work. Can you comment on this?
[/UPDATE]
-m32
, but not with-m64
(all8
s). – Psychosexual