I’m surprised that the list of issues does not include the implicit narrowing conversion from the string size to an int. (Especially since the list does complain about the implicit widening conversion in the str[] indexing expressions.)
int size = str.size();
Integer conversions need a great deal of care in C and C++ so this was the first thing that caught my attention. They had a lucky escape from UB in this case since narrowing conversions are implementation-defined, and an overflow to a negative index is caught by the loop guard (because it’s designed to cope with deliberate underflow due to an empty string). But the algorithm is quietly wrong for strings longer than INT_MAX.
I’d rephrase the title to, The problem with C++ safety: “it works” is often undermined by the language.
I’m surprised that the list of issues does not include the implicit narrowing conversion from the string size to an int. (Especially since the list does complain about the implicit widening conversion in the str[] indexing expressions.)
Integer conversions need a great deal of care in C and C++ so this was the first thing that caught my attention. They had a lucky escape from UB in this case since narrowing conversions are implementation-defined, and an overflow to a negative index is caught by the loop guard (because it’s designed to cope with deliberate underflow due to an empty string). But the algorithm is quietly wrong for strings longer than INT_MAX.
I’d rephrase the title to, The problem with C++ safety: “it works” is often undermined by the language.
score 1 · canonical