logoalt Hacker News

Panzerschrek • today at 1:58 PM • 3 replies • view on HN

Bool should be logically 1-bit, when stored in memory only least significant bit should be used and the rest is allowed to be garbage. Such approach gives compilers as much room for optimizations as possible. Forcing them writing some specific bit-pattern may lead to suboptimal code generation.


Replies

adrian_b • today at 3:20 PM

Bool is 1-bit, but that bit can be defined as signed or as unsigned.

If bool is defined as unsigned, casting it to any size of integers will give 0 for false and 1 for true (using the standard zero-extension operation that converts smaller unsigned integers to bigger unsigned integers).

If bool is defined as signed, casting it to any size of integers will give 0 for false and -1 for true (i.e. an all-1 bit pattern) (using the standard sign-extension operation that converts smaller signed integers to bigger signed integers).

Defining bool to ignore the other bits except the LSB leads to a lower performance on most processors, because in almost all instruction sets it is more efficient to test whether an integer is null or non-null, than to test the value of a bit.

The only efficient way to use a single bit and to ignore the others would be to store the boolean in the most-significant bit, i.e. in the sign bit of a signed integer, because testing the sign is normally as simple as testing whether a value is null. If this convention were used, a boolean result could be 0 for false and -1 for true, but in input arguments negative would be true and non-negative would be false.

➕ show 3 replies
rep_lodsb • today at 3:11 PM

That's how gcc does it (at least in this one case), but as TFA points out, this is not standard-conforming.

wat10000 • today at 3:12 PM

The in-memory representation is a completely different question. The language could easily say that true has an integer value of -1 while still storing it as a single bit.