Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
    
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading