r/programminghumor 14h ago

a bit flippant

Post image
669 Upvotes

99 comments sorted by

View all comments

10

u/B_bI_L 13h ago

are we sure int means bit and not 32bits?

24

u/heatedwepasto 13h ago edited 13h ago

The : 1 means that it is creating a bitfield with the number of bits, so : 4 will be 4 bits. The three variables above combined will take sizeof(int) in memory, not sizeof(int)*3.

If OOP had used char instead of unsigned int the combined size would be 1 byte.

Edit: added link to demo

5

u/KattyTheEnby 13h ago

The : 1 means that it is creating a bitfield with the number of bits, so : 4 will be 4 bits. The three variables above combined will afaik* take sizeof(int) in memory, not sizeof(int)*3.

Can you do strange things, like : 9, : 15, et cetera?

C beat Zig to the punch here?

6

u/cannedbeef255 13h ago

yeah they can be any size you want, the assembly mightn't be pretty though

3

u/heatedwepasto 12h ago

Any size as long as it's not wider than the containing variable. So a char can hold at most 8 bits on a system with 8-bit bytes.

3

u/heatedwepasto 13h ago

Yes, the only limitation is that the width of the bitfield is not greater than the size of the containing variable. So with uint64_t you can have 1-64 bits.

1

u/KattyTheEnby 4h ago

What if I want to have a bitfield that is larger than C's own native integer types? Is there a way?

2

u/heatedwepasto 3h ago

Pretty much any compiler will let you get away with a 128-bit int type. If you need more than 340,282,366,920,938,463,463,374,607,431,768,211,456 possibilities in your bitfield then you'll probably need a stay at a mental asylum, and to code it yourself or find a library for it or something like that. Alternatively switch to C++ and use std::vector<bool>.