Loading...
Pages: [1]   Go Down
Author Topic: for loop inside an if statement...  (Read 271 times)
0 Members and 1 Guest are viewing this topic.
Vancouver, Canada
Offline Offline
Jr. Member
**
Karma: 0
Posts: 76
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
if(condition)
{
   for(int i = 0, i < 1000, i++)
   {
        // do something dependent on the if condition
   }
}

Thanks
Logged

New Jersey
Offline Offline
Edison Member
*
Karma: 24
Posts: 2353
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

SF Bay Area (USA)
Online Online
Faraday Member
**
Karma: 78
Posts: 5454
Strongly opinionated, but not official!
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
   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:
   for(int i = 0; (i < 1000) && condition; i++)
   {
        // do something dependent on the if condition
   }
Logged

Vancouver, Canada
Offline Offline
Jr. Member
**
Karma: 0
Posts: 76
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Thanks a lot wildbil and westfw!
Logged

Pages: [1]   Go Up
Print
 
Jump to: