I have a code with 4-based integer that got MLE if I directly use
for(int i = 0; i < s.length() -10; i++)
but if I define an integer variable
int size = s.length();
and use this variable in for loop, it is accepted. why this happened?
When you call the function s.length(), the length of the string is calculated every time. If you store it in a variable, the method can just refer to it.
s.length() returns an unsigned integer, and 10 is an signed integer. When doing
s.length() - 10, 10 is cast to an unsigned integer. If the length of s is less than 10, this calculation causes underflow, and the result is an very large integer.
But if you use
int size = s.length(), the cast has done in this assignment statement, and you won't get error in the loop.