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.
Alignment of any struct (union) must be maximum or its multiple. of its members [*]. Since any (object) type may be a member, at least one struct (union) must have at least that type's alignment. it follows that all must meet the the maximum one.) Yes. 2. Alignment requirements for all structs _and_ unions are the same. same).
alignment requirements as each other. All pointers to union types shall have the same representation and alignment requirements as each other. alignment? have the same alignment requirements? of the struct or union. We must do something. This is something. Therefore, we must do this. and alignment requirements as each other. All pointers to union
The strictest (largest) fundamental alignment of any type is the alignment of max_align_t. The weakest (smallest) alignment is the alignment of the types char, signed char, and unsigned char, and equals 1. If an object's alignment is made stricter (larger) than max_align_t using _Alignas, it has extended alignment requirement.
Alignment of any struct (union) must be maximum or its multiple. of its members [*]. Since any (object) type may be a member, at least one struct (union) must have at least that type's alignment. it follows that all must meet the the maximum one.) Since the answer is no, the conclusion is unwarranted. 2.
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])
is sizeof(T)*N
.sizeof
is in units of char
; 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.T A[2];
, (char *)&A[1] - (char *)&A[0]
is equal to sizeof A[0]
.T
is no greater than sizeof(T)
(in fact it divides sizeof(T)
)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With