Go Down

Topic: for loop inside an if statement... (Read 566 times) previous topic - next topic

FardinB

Hello,

I want to know if I have a for loop inside an if statement, and the condition of the if statement goes false earlier than when the for can finish, will the for loop be terminated automatically?
Something like this:
Code: [Select]

if(condition)
{
   for(int i = 0, i < 1000, i++)
   {
        // do something dependent on the if condition
   }
}


Thanks

wildbill

No, it will not. If that's what you want, you'll have to check the condition in the for loop too.

westfw

No.  The condition is evaluated ONCE when the code reaches the IF statement, and then the whole for loop would be executed without ever checking the condition again.

There are a couple of alternatives:
Code: [Select]
   for(int i = 0; i < 1000; i++)
   {
        if (!condition) {
           break;
        }
        // do something dependent on the if condition
   }


or, since the second part of the FOR loop is a generic statement, you could do:

Code: [Select]
   for(int i = 0; (i < 1000) && condition; i++)
   {
        // do something dependent on the if condition
   }

FardinB


Go Up