Detect strings that consist of some a's followed by some b's
So:

// Note: str is a string.
//       containing "a"
//       So length = 1

while (str[i] == 'a' &amp;&amp; i &lt; str.length()) {
    i++;
}
// First Loop
//     str[0] == 'a' &amp;&amp; 0 &lt; 1
//     true &amp;&amp; true
//     true
//       So we enter the loop body and increment i to 1.
// Second Loop
//     str[1]  // access beyond the end of the string.
//             // thus undefined behavior.


If we swap the test around

while (i &lt; str.length() &amp;&amp; str[i] == 'a') {
    i++;
}
// First Loop
//     0 &lt; 1 &amp;&amp; str[0] == 'a'
//     true &amp;&amp; true
//     true
//       So we enter the loop body and increment i to 1.
// Second Loop
//     1 &lt; 1  &amp;&amp;  // The left hand side of the test is false
//                // &amp;&amp; is shortcut operator so the right hand
//                // side is not evaluated and the loop exited.