Detect strings that consist of some a's followed by some b's This program needs to detect strings in which the first few characters are 'a', than few 'b'.
Is it possible that in this implementation may be undefined behavior.

string str; 
while (cin &gt;&gt; str) {
    unsigned int i = 0;
    while (str[i] == 'a' &amp;&amp; i &lt; str.length()) {
        i++;
    }
    while (str[i] == 'b' &amp;&amp; i &lt; str.length()) {
        i++;
    }
    if (i == str.length()) {
        cout &lt;&lt; "ok" &lt;&lt; endl;
    } else {
        cout &lt;&lt; "Not ok" &lt;&lt; endl;
    }
}
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.