The following code crashes C++ with a runtime error:
#include
using namespace std;
int main() {
string s = \"aa\";
for (int i = 0; i
Actually, in the first version you loop for a very long time, as you compare i
to an unsigned integer containing a very large number. The size of a string is (in effect) the same as size_t
which is an unsigned integer. When you subtract the 3
from that value it underflows and goes on to be a big value.
In the second version of the code, you assign this unsigned value to a signed variable, and so you get the correct value.
And it's not actually the condition or the value that causes the crash, it's most likely that you index the string out of bounds, a case of undefined behavior.