Here's a sneaky little bug

Jonathan M Davis jmdavisProg at gmx.com
Fri Jun 24 11:43:34 PDT 2011


On 2011-06-24 11:28, Andrej Mitrovic 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.

The ternary operator has _very_ low precedence. I believe that the various 
assignment operators, throw, and the comma operator are the only operators 
with lower precedence. So, almost in all cases, _everything_ to the left of a 
ternary operator is evaluated before the ternary. So, unless it's by itself 
(like on the right-hand side of an assignment or as the argument to a 
function), you pretty much always want to put parens around it.

- Jonathan M Davis


More information about the Digitalmars-d mailing list