C++ crashes in a ‘for’ loop with a negative expression

s.length() is unsigned integer type. When you subtract 3, you make it negative. For an unsigned, it means very big.

A workaround (valid as long the string is long up to INT_MAX) would be to do like this:

#include <string>

using namespace std;

int main() {

    string s = "aa";

    for (int i = 0; i < static_cast<int> (s.length() ) - 3; i++) {

    }
}

Which would never enter the loop.

A very important detail is that you have probably received a warning “comparing signed and unsigned value”. The problem is that if you ignore those warnings, you enter the very dangerous field of implicit “integer conversion”(*), which has a defined behaviour, but it is difficult to follow: the best is to never ignore those compiler warnings.


(*) You might also be interested to know about “integer promotion”.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)