Doing two things at once
I like this bug that I found in a colon-separated path splitting function in some of our C++ code:
while (size_t pos = pathstr.find(":") != string::npos) { // split string at position pos, i.e. the next colon... }
I couldn't see the bug, so I re-wrote it without the cheeky 2-in-1 assign-and-compare:
while (true) { size_t pos = pathstr.find(":"); if (pos == string::npos) break; // split string at position pos... }
It worked immediately. What happens with the code above is that the path string
always gets chopped one character at a time, rather than at the colons. This is
because the !=
operator takes
precedence over the
assignment (=
) operator: the first level of evaluation effectively gives
while (size_t pos = true) ...
as long as there's a colon somewhere in the
string. Automatic type conversion then converts the boolean true
to an
integer 1
and the string gets chomped 1
character at a time until no more
colons are found.
Take the hint: don't try to do two things at once, even if you can.
Comments
Comments powered by Disqus