bool <=> int. WTF. (DIP0015)

Patrick Schluter Patrick.Schluter at bbox.fr
Fri Jul 5 23:01:20 UTC 2019


On Friday, 5 July 2019 at 21:45:00 UTC, lithium iodate wrote:
> On Friday, 5 July 2019 at 09:04:26 UTC, Patrick Schluter wrote:
>> On Friday, 5 July 2019 at 03:10:06 UTC, Exil wrote:
>>> On Thursday, 4 July 2019 at 16:31:11 UTC, Patrick Schluter 
>>> wrote:
>>>> that's the issue. D's bool type follows exactly C (C has 
>>>> bool since C99) and C++ way.
>>>> bool b; will behave exactly like your bool b = void;
>>>
>>> It doesn't have the same behavior. Currently DMD's codegen is 
>>> bad, sometimes it checks the entire byte value and other 
>>> times it only checks the first bit. All C/C++ compilers I've 
>>> used check the entire value, consistently.
>>
>> if the codegen does something like (x & 1) then it is indeed a 
>> BUG and should be corrected.
>
> Bug because it is inefficient or incorrect?
> To the best of my knowledge C does only mandate that _Bool must 
> be able to store 0 and 1, and  imposes no requirements on how 
> other representations have to be treated.

The standard says that other bit representations in the bool 
variable (uninitialised) is "undefined behaviour", so there is no 
further point in discussing about the validity of what the 
compilers do after that.

> GCC treats _Bool as having 2 valid representations and 254 trap 
> representations, so x == 1, x & 1 and x > 0 are all necessarily 
> equivalent given this assumption. Not sure about Clang, in my 
> quick test it always only checked the least significant bit.
>
> Does D really not have more specific requirements for bool? 
> (Does D even allow anything to have trap representations? There 
> doesn't really seem to be any info on that)

I played around a bit on godbolt and indeed the only compiler 
doing the (x & 1) test is llvm in non-optimized code, be it via 
ldc or via clang in C and C++. When optimizing it generates code 
that is more or less same as the other compilers but tries in 
most cases to only check the value of bit 0.
The other compilers are all over the place and sometimes they 
will generate code that assumes the value is only in bit 0, 
sometimes not, i.e. any non null value in the register will be 
seen as true and in other cases not.
Conclusion: as the C standard says, undefined behaviour and 
anything can happen.


More information about the Digitalmars-d mailing list