Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to break out of an if statement from a boolean inside the if statement [closed]

I have something like this

bool a = true;
bool b = true;
bool plot = true;
if(plot)
{
    if(a)
    {
        if(b)
            b = false;
        else
            b = true;
    //do some meaningful stuff here
    }
//some more stuff here that needs to be executed
}

I want to break out of the if statement that tests a when b turns false. Kind of like break and continue in loops. Any ideas? Edit: sorry forgot to include the big if statement. I want to break out of if(a) when b is false but not break out of if(plot).

like image 825
Chris Avatar asked Jul 18 '13 15:07

Chris


People also ask

How do you do a break in an if statement?

You'll put the break statement within the block of code under your loop statement, usually after a conditional if statement. In this small program, the variable number is initialized at 0. Then a for statement constructs the loop as long as the variable number is less than 10.

Does break go out of if statements?

breaks don't break if statements. A developer working on the C code used in the exchanges tried to use a break to break out of an if statement. But break s don't break out of if s. Instead, the program skipped an entire section of code and introduced a bug that interrupted 70 million phone calls over nine hours.

How do you break out of if statements but not for loops?

if statements are not loops; you don't 'break out' of them. When you use break inside an if statement, it will break out of the loop that directly encloses it (in this case, the for loop). break is not treated any differently inside an if block.

What happens if an if statement is false?

The most common and widely used statement is the if statement. It will compute if a statement is true or false. If it's true, it will execute the code. If it's false, it won't execute the code.


2 Answers

You can extract your logic into separate method. This will allow you to have maximum one level of ifs:

private void Foo()
{
   bool a = true;
   bool b = true;
   bool plot = true;

   if (!plot)
      return;

   if (a)
   {
      b = !b;
      //do something meaningful stuff here
   }

   //some more stuff here that needs to be executed   
}
like image 138
Sergey Berezovskiy Avatar answered Oct 14 '22 09:10

Sergey Berezovskiy


if(plot)
{
    if(a)
    {
        b= !b;
        if( b )
        {
            //do something meaningful stuff here
        }
    }
    //some more stuff here that needs to be executed
}
like image 43
Denise Skidmore Avatar answered Oct 14 '22 09:10

Denise Skidmore