calignment

Is there any difference between stating the "alignas" keyword in struct definition VS array of struct definition?


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?


Solution

  • You haven't placed alignas in the correct place in the first example, but:

    1. Aligning the first member of the 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
      
    2. 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