Say I have a struct named Particle
and I would like it to be aligned by 32bits, should I use the alignas
keyword when I specify the struct definition, like code below:
struct alignas(32) Particle {
// Total size: 16 bytes, but alignas(32) ensures 32-byte alignment
float x; // 4 bytes
float y; // 4 bytes
float z; // 4 bytes
float w; // 4 bytes
};
or should I specify it in the definition for the layouts where the structs reside, like this:
alignas(32) Particle particles[8]; // Array of 8 particles, 32-byte aligned
or should I do both?
You haven't placed alignas
in the correct place in the first example, but:
struct
will ensure that every instance of struct Particle
is aligned according to your specification:
struct Particle {
alignas(32) float x; // 4 bytes
float y; // 4 bytes
float z; // 4 bytes
float w; // 4 bytes
};
struct Particle particles[8];
... = &particles[0]; // aligned to 32
... = &particles[1]; // aligned to 32
struct Particle {
float x; // 4 bytes
float y; // 4 bytes
float z; // 4 bytes
float w; // 4 bytes
};
alignas(32) struct Particle particles[8];
... = &particles[0]; // aligned to 32
... = &particles[1]; // not aligned to 32