0

Why is the size of these two struct different depending on #include <stdbool.h> vs. typedef enum { false, true } bool; ?


#include <stdio.h>
#include <stdbool.h>
//typedef enum { false, true } bool;

struct x {
    bool a;
    int b;
    char c;
};

struct y {
    bool b;
    char a;
    int c;
};

int main(void) {

    struct x x;
    struct y y;

    printf("Size of struct x:\t %zu\n", sizeof(x));
    printf("Size of struct y:\t %zu", sizeof(y));

    return 0;
}

With #include <stdio.h> the results on my machine (Mac, Intel):

Size of struct x:    12
Size of struct y:    8

I assume the size difference (i.e. 8 and 12) here is due to C utilizing some kind of memory structure padding.

With typedef enum { false, true } bool; the result:

Size of struct x:    12
Size of struct y:    12

Note: The question is not about structured padding (read more about that here and here), but why #include <stdbool.h> vs. typedef enum { false, true } bool; gives different results to the same lines of code.

joekash
  • 19
  • 5

0 Answers0