Reputation: 15093
On VC++, why does the compiler only pad struct when non-char datatypes are used?
I.e.
struct TEST
{
char a[7];
};
struct TEST2
{
__int32 a;
char b[7];
};
sizeof(TEST); // Returns 7
sizeof(TEST2); // Returns 12
Upvotes: 1
Views: 231
Reputation: 489988
It comes down to the fact that sizeof(char) == 1
-- always.
Arrays are required to be contiguous, so in an array of char (if it's large enough), you end up with elements at every possible alignment. Since the compiler/hardware has to make that work, there can't be a need to insert padding to deal with char
in something like a struct
either.
Now, that's not to say that a compiler couldn't insert padding. For example, it might be able to improve performance by doing so, even with an array of char. For example, given your struct
definition, it would be perfectly acceptable for the compiler to pad your array of 7 char's with one more to make the sizeof the struct 8 -- a nice, neat power of 2.
On some hardware, you'd be likely to see that. As it happens, the Intel hardware supported by VC++ doesn't really benefit much from things like that, so you're unlikely to see it there.
Upvotes: 2