Here's a sneaky little bug
Steven Schveighoffer
schveiguy at yahoo.com
Fri Jun 24 11:49:24 PDT 2011
On Fri, 24 Jun 2011 14:28:45 -0400, Andrej Mitrovic
<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.
I can never remember precedence for ?:, so quite often I will
over-parenthesize those expressions. I also typically over-parenthesize
any expressions involving logical operations (i.e. & and |)
Rule of thumb -- minimal parentheses that establish order of precedence,
even if unnecessary, don't ever hurt :)
But in any case, I'm really surprised "state is: " ~ false works at
all... Since when can you append non-character types to strings? This is
bound to result in bugs, since many people come from languages where
appending a non-string type to a string results in a conversion to a
string.
I'd expect "state is: " ~ false to result in "state is: false" if it
compiles at all. This may not be a bug, but it probably warrants an
enhancement. D goes through great pains to avoid automatic string
conversion, I think it should reject any attempts at it, even if they are
accidental.
-Steve
More information about the Digitalmars-d
mailing list