5 ms·
It's interesting that booleans are stored as 0 or -1 [1]. I wonder what drove that decision. I just checked, and Rust's LLVM stores booleans as 0 or 1. [1] htt
by smaddox 8y ago
It's interesting that booleans are stored as 0 or -1 [1]. I wonder what drove that decision. I just checked, and Rust's LLVM stores booleans as 0 or 1.
[1] https://cranelift.readthedocs.io/en/latest/ir.html#boolean-types https://cranelift.readthedocs.io/en/latest/ir.html#boolean-t...
- sunfish 8y agoA typical Rust bool would use `b1`, which doesn't have an observable representation.
- sunfish 8y agoAlso, the [bint instruction](https://cranelift.readthedocs.io/en/latest/ir.html#inst-bint https://cranelift.readthedocs.io/en/latest/ir.html#inst-bint) converts a bool value to an integer 0 or 1.
- steveklabnik 8y agoWe did, eventually, after years, define it as a full byte though. https://github.com/rust-lang/rust/pull/46156 https://github.com/rust-lang/rust/pull/46156
- KMag 8y agoWell, for one, if true is -1 (using two's complement), then a bunch of conditionals and bit-twiddling become more simple. For instance: x = some_bool ? a : b; can be compiled as a branchless: x = (some_bool & a) | (~some_bool & b); This is why Forth also represents true as -1.
- pcwalton 8y agoAlso why SIMD fairly universally uses -1 for true. C arguably picked the wrong semantics here. Hardware picks up the slack, however, with the setcc instructions on x86, csinc on AArch64, etc.
- eridius 8y agoThat would only be true if `a` is guaranteed to be a non-zero value though, right? e.g. `x = some_bool ? 0 : 1` would not be able to be represented that way.
- repsilat 8y agoIt works for me. Note that `|` is a bitwise-or (not that it really matters, it just removes a branch) const True = -1 const False = 0 const ternary = (condition, left, right) => \ (condition & left) | (~condition & right) ternary(True, 0, 1) // 0 ternary(False, 0, 1) // 1
- eridius 8y agoOh right, because the right-hand side evaluates to 0 as well in this case. Makes sense.
- cpeterso 8y agoBoolean true is -1 in Visual Basic, too: https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/data-types/boolean-data-type https://docs.microsoft.com/en-us/dotnet/visual-basic/languag...
- perl4ever 8y agoIt was traditional in earlier BASICs too; I think I remember it being the case in QuickBASIC and AmigaBASIC. I assume someone once upon a time thought it was a nice thing for ~x to be equal to !x.