Krishnamurthy
Krishnamurthy

Reputation: 715

compound condition in for loop

What is the difference between the following two constructs? I am getting a different output for each:

for (int counter = 0; (counter < numberOfFolds) && counter != currentFold; counter++)
        {
            if (instances[counter] < minimum)
            {
                return (currentFoldHasAtleastMinimum && true);
            } 

        }

AND

for (int counter = 0; (counter < numberOfFolds); counter++)
        {
            if (counter != currentFold)
            {
                if (instances[counter] < minimum)
                {
                    return (currentFoldHasAtleastMinimum && true);
                } 
            }
        }

Essentially, the second block of code, simply breaks the compound condition in the for loop and takes it inside using an additional if statement (I may be missing something very fundamental here, and it may be really stupid, but I thought they were the same).

Please help. It appears that they are in fact not the same, and I cannot figure out why.

Upvotes: 1

Views: 2472

Answers (2)

wsanville
wsanville

Reputation: 37516

In the first example, when counter is equal to currentFold the loop terminates.

In the second example, the loop will continue when that condition is met, and instead will only terminate when counter < numberOfFolds is false.

Upvotes: 1

dlev
dlev

Reputation: 48596

The first condition will end the loop as soon as either sub-condition becomes false (so counter >= numberIfFolds or counter == currentFold). The second loop will only terminate when counter >= numberOfFolds. It will, however, check if counter == currentFold and skip executing those statements if it is. The loop will continue, though.

Upvotes: 2

Related Questions