4

This program:

struct alignas(4) foo {};
int main() { return sizeof(foo); }

returns 4, with GCC 10.1 and clang 10.1, and icc 19.0.1 .

That makes me wonder - is it mandatory for alignas() to affect sizeof() this way? i.e. increase the size beyond what the structure would originally be sized at? Or - is this change just the implementation's prerogative?

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
einpoklum
  • 118,144
  • 57
  • 340
  • 684
  • 1
    I remember having this discussion with my programming instructor. IIRC, since arrays are required to have no gaps between elements, structures must be padded to make their size a multiple of the alignment. – HolyBlackCat May 17 '20 at 18:32
  • 3
    What would `foo f[10];` do if it wouldn't affect the size that way? – Eljay May 17 '20 at 18:33
  • 3
    _"...When applied to a class type, the result is the size of an object of that class __plus any additional padding required to place such object in an array__...."_ source: https://en.cppreference.com/w/cpp/language/sizeof – Richard Critten May 17 '20 at 18:34
  • @RichardCritten: So, it _is_ mandatory then? – einpoklum May 17 '20 at 18:35
  • That's my understanding but don't have a Standard reference to hand. – Richard Critten May 17 '20 at 18:38

1 Answers1

6

is it mandatory for alignas() to affect sizeof() this way? i.e. increase the size beyond what the structure would originally be sized at?

Yes. Size of a class is defined in terms of distance between elements of an array of that type. There is no padding between elements of an array (except for padding that is within the type and therefore part of the size). If size was less than alignment, then it would not be possible for adjacent array elements to satisfy that alignment.

Size must be at least as much as alignment, and it must be a multiple of the alignment, and alignments are always powers of two.

eerorika
  • 232,697
  • 12
  • 197
  • 326