Search code examples
c++for-loopbreakgotonested-if

How to exit from nested if-else statements inside a for loop?(C/C++)


I have a for loop in my program that is my program's main loop and it should work in real time. There are some if-else statements inside the loop too. I want if any if conditions satisfied, the program exits from if-else statements and retry the for loop.

for(;;)
{
    if(condition_one)
    {
        do_one();
    }
    else if(condition_two)
    {
        do_two();
    }
    else 
    {
        do_three();
    }

    rest_of_program();
}

I tried to write the above code like this:

for(;;)
{
    if(condition_one)
    {
        do_one();
        goto exitt; 
    }
    else if(condition_two)
    { 
        do_two();
        goto exitt;
    }
    else 
    {
        do_three(); 
    }
    exitt:
    rest_of_program();
}

But it seems there is a problem and my program doesn't work! Did I do something wrong? Or is there a better idea?


Solution

  • I think you are overcomplicating the matter. The thing is that this code:

    for(;;)
    {
        if(condition_one)
        {
            do_one();
            goto exitt; 
        }
        else if(condition_two)
        { 
            do_two();
            goto exitt;
        }
        else 
        {
            do_three(); 
        }
        exitt:
        rest_of_program();
    }
    

    is equivalent to this one:

    for(;;)
    {
        if(condition_one)
        {
            do_one();
        }
        else if(condition_two)
        { 
            do_two();
        }
        else 
        {
            do_three(); 
        }
        rest_of_program();
    }
    

    The individual blocks of the if-else are mutually exclusive and no matter which one is executed, after that there will be rest_of_program and after that the loop continues.