Question

I'm looking at this Java code:

        while (n-- != 0) {
            if (searchMe.charAt(j++) != substring.charAt(k++)) {
                continue test;
            }
        }

I am confused about when, exactly, the n-- operation takes place. Is it after the if statement?

Was it helpful?

Solution

The n-- operation happens each time the while condition is evaluated; specifically when the left-hand side of the != operator is evaluated. It has nothing to do with the if statement. The while condition is evaluated at the start of each loop iteration; if it evaluates to true, then the body of the while loop (the if statement) is executed, but that's well after the n-- operation has finished. (But of course, then there's the next loop iteration.)

OTHER TIPS

When the while loop runs for the first time, the value of n is checked if its not equal to zero(because it is post decrement).

Once the condition is evaluated, i.e. after it comes inside the while loop, the value of n will be decremented by one(n-1). And this new value will be used inside the while loop for that particular iteration.

Next iteration when the while loop check the condition, value (n-1) is checked if its equal to zero and so on.

-- or ++ operators if put after operand will happen after the statement that contains it finishes. If put before operand then it will happen before that statement.

In this case the statement is while so it will happen after it, meaning after evaluation of condition in the while statement.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top