Would this union work if char had stricter alignment requirements than int?
Question
Recently I came across the following snippet, which is an attempt to ensure all bytes of i
(nad no more) are accessible as individual elements of c
:
union {
int i;
char c[sizeof(int)];
};
Now this seems a good idea, but I wonder if the standard allows for the case where the alignment requirements for char
are more restrictive than that for int
.
In other words, is it possible to have a four-byte int which is required to be aligned on a four-byte boundary with a one-byte char
(it is one byte, by definition, see below) required to be aligned on a sixteen-byte boundary?
And would this stuff up the use of the union above?
Two things to note.
I'm talking specifically about what the standard allows here, not what a sane implementor/architecture would provide.
I'm using the term "byte" in the ISO C sense, where it's the width of a
char
, not necessarily 8 bits.
Solution
No type can ever have stricter alignment requirements than its size (because of how arrays work), and sizeof(char)
is 1.
In case it's not obvious:
sizeof(T [N])
issizeof(T)*N
.sizeof
is in units ofchar
; all types are represented as a fixed number of bytes (char
), that number being their size. See 6.2.6 (Representation of Types) for details.- Given
T A[2];
,(char *)&A[1] - (char *)&A[0]
is equal tosizeof A[0]
. - Therefore the alignment requirement for
T
is no greater thansizeof(T)
(in fact it dividessizeof(T)
)
OTHER TIPS
Have a look at this thread. There, I questioned the usefulness of C Unions and there are some interesting insights. The important thing is that the Standard does not ensure the alignment of the different fields at all!
EDIT: paxdiablo, just noticed you were one of the guys answering that question, so you should probably be familiar with this limitation.