BiagioF
BiagioF

Reputation: 9735

Memory Alignment Guarantee

Is the following code cross-compilable?

struct Foo {
  alignas(1) char c1;
  alignas(1) char c2;
  alignas(4) int i;
};
static_assert(sizeof(Foo) == (sizeof(int) + 4), "No cross-compilable");

In other words, is it guaranteed that sizeof(Foo) == (sizeof(int) + 4) for whatever architecture/platform?

Upvotes: 1

Views: 173

Answers (1)

1201ProgramAlarm
1201ProgramAlarm

Reputation: 32727

Not it is not guaranteed. This will work on many architectures today, but on a system with 8-byte int (aligned on an 8-byte boundary) this won't work. In that case, though, you should get a compiler diagnostic because you're trying to apply a less strict alignment to an int; see [dcl.align].

Upvotes: 2

Related Questions