logoalt Hacker News

cogman10 • today at 1:25 PM • 2 replies • view on HN

The way C handles (prior to C23) booleans is pretty close to how you'd handle booleans in assembly.

CPUs don't have types, everything is integers or floats. You do your work on registers which have fixed sizes. CPUs have built in instructions for "is this register not zero" which leaks into C. 1 is true in C, but so is 2.

Also, single bits are rarely used for booleans because it requires more CPU power to extract a single bit. Everything is byte aligned at a minimum.

When doing something like network code, if you want to store a bunch of booleans you are typically going to either pack them into a byte, or you'll burn the extra bits and send a single byte for the boolean value. Typically this was flags and masks.


Replies

quikoa • today at 3:32 PM

> Also, single bits are rarely used for booleans because it requires more CPU power to extract a single bit.

Not necessarily, on modern CPUs memory access is often the bottleneck. If you have many bits storing these in a bitarray can be quite beneficial for performance.

xhroot • today at 1:47 PM

> single bits are rarely used for booleans

SQL Server still has no boolean type and groups bits in the same row into a byte if possible.