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.

  1. I'm talking specifically about what the standard allows here, not what a sane implementor/architecture would provide.

  2. I'm using the term "byte" in the ISO C sense, where it's the width of a char, not necessarily 8 bits.

Was it helpful?

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]) 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.
  • Given T A[2];, (char *)&A[1] - (char *)&A[0] is equal to sizeof A[0].
  • Therefore the alignment requirement for T is no greater than sizeof(T) (in fact it divides sizeof(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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top