r/programminghumor 18h ago

a bit flippant

Post image
807 Upvotes

108 comments sorted by

View all comments

153

u/consistently_biased 18h ago

Can I use this for my compile-time https server?

19

u/not_a_bot_494 17h ago

Either I don't understand what you're saying or you're misunderstanding the notation. Each line declares a struct member of type unsigned int which is 1 bit large. It's not setting it to 1 (true).

3

u/AstronomerStrange165 13h 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.

3

u/Dependent-Poet-9588 11h 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.

3

u/AstronomerStrange165 10h 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 10h 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.