Search code examples
ctypesalignmentportability

C - get type alignment portably


I'm writing really small interpreter for a very simple language, which allows for simple structure definitions (made of other structures and simple types, like int, char, float, double and so one). I want fields to use as little alignment as possible, so using max_align_t or something similar is out of question. Now, I wonder if there is a nicer way to get alignment of any single type other than this:

#include <stdio.h>
#include <stddef.h>

#define GA(type, name) struct GA_##name { char c; type d; }; \
    const unsigned int alignment_for_##name = offsetof(struct GA_##name, d);

GA(int, int);
GA(short, short);
GA(char, char);
GA(float, float);
GA(double, double);
GA(char*, char_ptr);
GA(void*, void_ptr);

#define GP(type, name) printf("alignment of "#name" is: %dn", alignment_for_##name);

int main() {
GP(int, int);
GP(short, short);
GP(char, char);
GP(float, float);
GP(double, double);
GP(char*, char_ptr);
GP(void*, void_ptr);
}

This works, but maybe there is something nicer?


Solution

  • This is probably not very portable, but GCC accepts the following:

    #define alignof(type) offsetof(struct { char c; type d; }, d)
    

    EDIT: And according to this answer, C allows casting to anonymous struct types (although I'd like to see this statement backed up). So the following should be portable:

    #define alignof(type) ((size_t)&((struct { char c; type d; } *)0)->d)
    

    Another approach using GNU statement expressions:

    #define alignof(type) ({ \
        struct s { char c; type d; }; \
        offsetof(struct s, d); \
    })