How can I restart while loop after certain condition (if) satisfied in c++?

70,117

Your question isn't very detailed so it's a little hard to tell what exactly do you want.

If you want the while loop to go to the next iteration after any error has fired, you should use the continue statement:

while( something )
{
    if( condition )
    {
        //do stuff
        continue;
    }
    else if( condition 2 )
    {
        //do other stuff
        continue;
    }
    <...>
}

If nothing else than these ifs is inside the loop, and the conditions are integer values, you should consider using switch instead:

while( condition )
{
    switch( errorCode )
    {
        case 1:
        //do stuff;
        break;
        case 2:
        //do other stuff;
        break;
        <...>
    }
}

If you want to completely restart the cycle... well this is a little harder. Since you have a while loop, you can just set the condition to it's starting value. For example, if you have a loop like this:

int i = 0;
while( i < something )
{
    //do your stuff
    i++;
}

then you can "reset" it like this:

int i = 0;
while( i < something )
{
    //do your stuff
    if( something that tells you to restart the loop )
    {
        i = 0;//setting the conditional variable to the starting value
        continue;//and going to the next iteration to "restart" the loop
    }
}

However, you should be really careful with this, it's easy to get an infinite loop accidentally.

Share:
70,117
fhuseynli
Author by

fhuseynli

Software Engineer with expertise in CI/CD, DevOps and Tool Development

Updated on July 09, 2022

Comments

  • fhuseynli
    fhuseynli almost 2 years

    I have a lot of if statements in while loop, program has to print error messages according to conditions, but if there are more than one error it has to be only one of them.

  • SingerOfTheFall
    SingerOfTheFall over 11 years
    Hm, I believe this is what the OP needs to get rid off actually.
  • fhuseynli
    fhuseynli over 11 years
    it is not about all integer, command includes string, integer, double. According to priority of the error, only one error has to be appeared on terminal. but mine is like puts every error on terminal
  • SingerOfTheFall
    SingerOfTheFall over 11 years
    @user, then just use else ifs with a continue statement in each to go to the next iteration after any error is put.
  • Shashwat
    Shashwat over 11 years
    In the first code, no need of continue statement
  • SingerOfTheFall
    SingerOfTheFall over 11 years
    @Sha, I was waiting for this comment. We don't know if there is any other code after a number of if statements. If there is no - you are right. If there is - the continue is needed.
  • Shashwat
    Shashwat over 11 years
    You are right. I also thought so. But he didn't write any code. So we didn't know.