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.
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.
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
}
}
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.
Instead of an if, use a switch statement. You can break out of a switch at any point. This isn't a very practical solution... but it works.
for(..;..;..)
{
switch(boolean_expression) { //break just leaves this switch statement
case 0: //false is 0
break;
default: //true is not zero
//statements
if(something)
break;
//statements you want to skip
break;
}
//statements
}
If I understand your question, that you want to write a statement inside if and goto your marked statements only if that condition is true, then a goto statement can be useful, if for instance //statements only need to be run if the condition is true:
for(..;..;..)
{
if(true)
{
goto dothis;
}
/* other statements */
return A;
dothis:;
//statements
return B;
}
The //statements need not be in the for loop with goto, for example:
for(..;..;..)
{
if(true)
{
goto dothis;
}
/* other statements */
}
return A;
dothis:;
//statements
return B;