"Andrej Mitrovic" <andrej.mitrov...@gmail.com> wrote in message news:mailman.1195.1308940135.14074.digitalmar...@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.