Here's a sneaky little bug
Nick Sabalausky
a at a.a
Fri Jun 24 12:08:29 PDT 2011
"Andrej Mitrovic" <andrej.mitrovich at gmail.com> wrote in message
news:mailman.1195.1308940135.14074.digitalmars-d at puremagic.com...
> 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.
Yea, I've learned to always use parens around any ?: inside a larger
expression (changing ?: without parens works fine, though). But that's a
particularly bad scenario. Filed under "That damn implicit int->char
conversion strikes again." Overly permissive implicit conversions are soooo
C.
Unfortunately, I don't think this general gotcha with ?: would be fixed with
an order-of-operations change (it'd be nice if it could). Arithmetic and
concat have higher precidence than comparison, so if we made ?: higher
precidence than arithmetic/concat then we'd have to be very careful to do
this:
(a==b)?c:d
every time we use a comparison for the ?:'s condition.
More information about the Digitalmars-d
mailing list