(too) clever use of bool in Solution 7.1 StringToInt(), and use of int/size_t?

#1

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.

0 Likes

#2

Hey Jason,

First of all, personally I like this discussion you brought since this shall be an interesting topic. After I re-examined the code, I agree with your saying that this is a little too clever, and readability should always trump succinctness. Therefore a ternary operator checking s[0] == '-' is added in the updated code.

About the size_t and int usages, I always falling into the dilemma of choosing one of these two. Recently I decided to use int always since the potential bug when you use size_t to iterate a loop backwardly (an infinite loop may occur), and it makes no sense to use size_t for forward loop and int for backward loop. In this case, simplicity trumps the warning messages from compiler :smile:

Thanks for bring this up, and it shall be a good topic for readers to discuss.

0 Likes