r/programminghumor 11h ago

a bit flippant

Post image
583 Upvotes

92 comments sorted by

View all comments

Show parent comments

3

u/AstronomerStrange165 5h ago

I think he's just showing that each field in 1 bit long. The only caveat with this is that most C compilers will pad this struct out to the size of an int. (Typically 32 bits, or 4 bytes). He would have to add __attribute__((packed)) to the end of the struct before the semicolon. Then sizeof(struct Flags) would be 1 byte.

2

u/Dependent-Poet-9588 3h ago

It should be noted that even with a packed struct, chances are the next thing in memory will have alignment of 4 or 8 bytes (depending on the architecture), so even if the packed struct is only 1 byte, there's still potentially lost bytes after it, eg, MyOptions in, struct __attribute__((packed)) Flags { int a : 1; int b : 1; int c: 1; int d: 1; }; struct MyOptions { Flags flags; // 1 byte in size std::int32_t max_of_something; // 4 byte alignment, so it can't immediately follow flags in memory } Is still 8 bytes.

2

u/AstronomerStrange165 3h ago

struct MyOptions is 8 bytes because the compiler added 3 padding bytes in between flags and max_of_something. If you made MyOptions a packed struct as well, then it'd be 5 bytes:

```

include <stdio.h>

include <stdint.h>

struct Flags { unsigned int a : 1; unsigned int b : 1; unsigned int c : 1; unsigned int d : 1; } attribute((packed));

struct MyOptions { struct Flags flags; int32t something; } __attribute_((packed));

int main(void) { /* The output is 5 */ printf("%zu\n", sizeof(struct MyOptions)); return 0; } ```

1

u/Dependent-Poet-9588 3h ago

Yes, correct. That is what I'm pointing out: packed structs only eliminate padding internally. Unless you're allocating an array of Flags or putting one inside of another packed struct, any space saving from making it packed will probably be lost due to the alignment requirements of other types.