Stand by...

Funny little nasty bug

Some time ago I was writing some piece of code in which there was a part where I have to concatenate strings differently depending on some flag. Easy thing. So I wrote some few lines of code and to my great surprise it does not work.

I wrote something like this:

<code class="cpp">bool flag;
/* ... some code setting flag ... */
std::string out = "path";
out += "/" + flag ? "X" : "Y";</code>

What I was trying to achieve is rather obvious but if you think that out string contains “path/X” or “path/Y” you are wrong! True is result was always “pathX”.

The reason for that is simple. Compiler (because of operator precedence) treats above code as:

<code class="cpp">out += ("/" + flag) ? "X" : "Y";</code>

instead of

<code class="cpp">out += "/" + (flag ? "X" : "Y");</code>

When I look at this bug right now it look easy, but I spend few minutes on few lines of code to catch it.

0 Comment(s). Add a comment or Trackback

Leave a comment ↓

Welcome back, (change)

submitting...