Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Skipping the rest of the current `for` iteration and beginning a new one.

Tags:

c++

for-loop

Consider this C++ code

for(int i=0; i<=N; ++i)

{

if(/* Some condition 1 */) {/*Blah Blah*/}

if(/* Some condition 2  */){/*Yadda Yadda*/}

}

Is there any keyword/command so that if condition 1 evaluates to true and execution of /*Blah Blah*/ I can skip the rest of the current iteration and begin a new iteration by incrementing i.

The closest thing I know to this kind of statement skipping is break but that terminates the loop entirely.

I guess one could do this by using some flags and if statements, but a simple keyword would be very helpful.

like image 515
smilingbuddha Avatar asked Sep 22 '11 21:09

smilingbuddha


People also ask

What skips the current iteration of the loop?

The continue statement can be used if you need to skip the current iteration of a for or while loop and move onto the next iteration.

How do you skip iterations in C++?

Break and continue are loop control statements in C++ that are used to exit from the loop or skip any iteration in the loop.

How do you skip something in a loop?

So, use continue when you want to skip the rest of the current loop iteration, and use break when you want to skip all remaining loop iterations.

Which of the following statements skip the execution of the remaining part of the loop?

Answer. The continue statement is used inside loops. When a continue statement is encountered inside a loop, control jumps to the beginning of the loop for next iteration, skipping the execution of statements inside the body of loop for the current iteration.


2 Answers

Use the keyword continue and it will 'continue' to the next iteration of the loop.

like image 109
0x5f3759df Avatar answered Oct 23 '22 10:10

0x5f3759df


This case seems better suited for if..else.. than a continue, although continue would work fine.

for(int i=0; i<=N; ++i)
{
    if(/* Some condition 1 */)
    {/*Blah Blah*/}
    else if(/* Some condition 2  */)
    {/*Yadda Yadda*/}
}
like image 24
Kashyap Avatar answered Oct 23 '22 11:10

Kashyap