Even if the Standard guarantees true == 1 and false == 0, I wonder whether using (abusing?) that fact in the manner of the given solution might be considered “too clever” in an interview or whether it would be pointed out in a code review? It’s a matter of opinion but I suspect it may not break down to 50-50 so I’ll post here for discussion. Maybe it’s a common idiom that I just haven’t seem before.
bool is_negative = s[0] == '-';
for (int i = is_negative; i < s.size(); ++i) {
Since the ternary operator operator wouldn’t cause the line to be too long in this context, I’d personally use it in such a situation because I think it would be more readable. (I’m less concerned about portability to old compilers where people may have typedef’d/enumerated bool differently.)
(the code is the same in 1.4.8 of the book and on Google Code)
On an even more nitpicky but related note, sometimes the book uses type int
when traversing a string
, sometimes size_t
. (e.g. size_t in Solution 7.6). In this particular case, maybe it’s in the name of a possible efficiency boost (since a valid encoded integer will only take up so many characters) but I suspect it’s more likely a case of momentarily falling back to the old ways we first learned rather than the new best practices of updated coding standards since C99? For consistency’s sake, I like to use size_t throughout my code unless there’s some reason not to.