Here's a sneaky little bug

KennyTM~ kennytm at gmail.com
Fri Jun 24 12:07:55 PDT 2011


On Jun 25, 11 03:03, KennyTM~ wrote:
> On Jun 25, 11 02:44, Jimmy Cao wrote:
>>
>>
>> On Fri, Jun 24, 2011 at 1:28 PM, Andrej Mitrovic
>> <andrej.mitrovich at gmail.com <mailto:andrej.mitrovich at gmail.com>> wrote:
>>
>> import std.stdio;
>>
>> void main()
>> {
>> bool state = false;
>> writeln("state is: " ~ state ? "true" : "false");
>> }
>>
>> writes:
>> true
>>
>> Whoa, what happened? Well, this should explain things:
>>
>> bool state = false;
>> auto str = "bla" ~ state;
>>
>> What (I assume) happens is the state boolean is converted to an int,
>> and since chars are ints in disguise and interchangeable you can
>> concatenate them with strings.
>>
>> So the original code acted like it was written like this:
>> bool state = false;
>> writeln(("state is: " ~ state) ? "true" : "false");
>>
>> And what we wanted was this:
>> bool state = false;
>> writeln("state is: " ~ (state ? "true" : "false"));
>>
>> Anyway I just wanted to share how forgetting parens can introduce
>> bugs in code.
>>
>>
>> Why can ints be so easily concatenated with strings in the first place?
>
> Because 'int' is convertible to a 'dchar'. (I have a patch based on
> Value Range Propagation against this, but it breaks a lot of druntime
> and Phobos code.)

... although this won't prevent the original bug because bool = [0, 1] 
is convertible to any char type under the current implementation.

I think this needs to prevent automatic conversion of bool -> xchar, i.e.

integer type <---> char type  (ok under VRP)
integer type <---> bool       (ok under VRP)
    char type <-/-> bool       (disallowed)

converting a 'bool' to an char type is seldom meaningful anyway.


More information about the Digitalmars-d mailing list