Yet another slap on the hand by implicit bool to int conversions

Timon Gehr timon.gehr at gmx.ch
Sun Jun 19 15:20:38 PDT 2011


Peter Alexander wrote:
> On 19/06/11 10:51 PM, Timon Gehr wrote:
>> Andrej Mitrovic wrote:
>>> So I've had a pretty fun bug today when porting some code over to D.
>>> When I port C code to D, first I do a one-to-one translation and make
>>> sure everything works before I try to make use of any D features.
>>>
>>> Here's a function snippet, try to figure out what's wrong with the
>>> code (don't worry about type definitions or external variables yet):
>>>
>>> http://codepad.org/gYNxJ8a5
>>>
>>> Ok that's quite a bit of code. Let's cut to the chase:
>>>
>>> if (mmioRead(hmmio, cast(LPSTR)&drum, DRUM.sizeof != DRUM.sizeof))
>>> {
>>>      mmioClose(hmmio, 0);
>>>      return szErrorCannotRead;
>>> }
>>> [snip.]
>>
>> Maybe DMD could warn on nonsense of the form x != x.
>>
>>
>> Timon
>
> That would help in this particular case, but not in general.

I claim that in this particular case the x != x was more of a problem than the
implicit conversions.
Implicit conversions from boolean to int don't hurt in general.
But they are also not generally useful, just if you want to use arithmetics on bools:

bool b;
int i=b; // you seldom want to do this

int month;
int daysinmonth = month==1?28:30+((m&1)==(m>6)); // kinda neat, implicit
conversions in 2 places

A possible resolution could be to just disallow direct implicit conversion but
allow bools in arithmetic expressions. That would be special casing though.


Timon


More information about the Digitalmars-d mailing list