Say I have a struct named Particle and I would like it to be aligned by 32bits, should I use the align 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?
>Solution :
You haven’t placed alignas in the correct place in the first example, but:
- Aligning the first member of the
structwill ensure that every instance ofstruct Particleis 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 - Aligning only the instance will only ensure that the first instance in your array is aligned according to your specification.
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