Here's a sneaky little bug

Brad Anderson eco at gnuk.net
Fri Jun 24 11:40:50 PDT 2011


This article talks a lot about this common bug:
http://www.viva64.com/en/a/0072/

On Fri, Jun 24, 2011 at 12:28 PM, 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.
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20110624/8e362ccb/attachment.html>


More information about the Digitalmars-d mailing list