Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic Programming

Tags:

c

I have a structure like this

for(..;..;..)
{
    if(true)
    {

    }
    //statements

} 

I want to write a statement inside if except goto that will send the control only outside if and execute statements that I have marked.

like image 238
Avinash Sharma Avatar asked May 11 '26 17:05

Avinash Sharma


2 Answers

A common way to handle this situation is to put the body of the if statement into a separate function, and then return from the middle of the function if, for some reason, the function is unable to finish. After the function returns, the remainder of the statements in the for loop will run.

void foo(void)
{
    //statements
    //statements

    if ( something_bad_happened )
        return;

    //statements
    //statements

    if ( some_other_bad_thing_happened )
        return;

    //statements
    //statements
}

void bar(void)
{
    for(..;..;..)
    {
        if ( some_foo_is_needed )
            foo();

        //statements
        //statements
    }
}
like image 176
user3386109 Avatar answered May 14 '26 08:05

user3386109


You can put your if inside a dummy do..while loop like this:

for(..;..;..)
{
    do
    {
        if ()
        {
            //use break somewhere here according to your logic
        }
    }while(false);

    //statements
} 

This will cause the break to only skip the inner do..while loop.

The condition is false in do..while so that the loop runs only once as is expected in case of a normal if. The loop is there just to allow a break in the middle.

like image 35
tapananand Avatar answered May 14 '26 09:05

tapananand