Breaking out of nested if

CK920 picture CK920 · Feb 26, 2015 · Viewed 19.8k times · Source

I have a bit of code that contains nested if statements:

if(numberOfNeighbors == 1){

                //go through comparison again, add Pixel(i,j) to current linked list -> complist[numberOfComponents]
                    //  break out of large check ??

                    if(ji.getPixelColor(i, j) == (ji.getPixelColor(i-1,j-1))){ //compare to top left
                        complist[numberOfComponents].addFirst(new Pixel(i,j,numberOfComponents)); break; 
                    }
                    if(ji.getPixelColor(i, j) == (ji.getPixelColor(i,j-1))){ // compare to top
                        complist[numberOfComponents].addFirst(new Pixel(i,j,numberOfComponents)); break;
                    }

                    if(ji.getPixelColor(i, j) == (ji.getPixelColor(i+1,j-1))){ // compare to top right
                        complist[numberOfComponents].addFirst(new Pixel(i,j,numberOfComponents)); break;
                    }
                    if(ji.getPixelColor(i, j) == (ji.getPixelColor(i-1,j))){ // compare to left
                        complist[numberOfComponents].addFirst(new Pixel(i,j,numberOfComponents)); break;
                    }
} // end of if(numberOfNeighbors == 1)

Basically what I would like to do, however inefficient this may be, is compare a something 4 times, but if it turns out it is a match, break out of the set of the 4 nested if statements, as well as the outer if statement.

Will this work? or will it just break out of the nested if its currently at and continue to the next until its gone through all 4?

Answer

Prudhvi picture Prudhvi · Feb 26, 2015

IMPORTANT: break statements are used to come out of loops but not branches

I understood your question but use break statement to go out of loops like for, while, do while. You can go out of if statement when the condition is satisfied and statements inside the if branch are executed. If you don't want to check for other conditions when your first if is satisfied you have to use if else branches instead of using 4 if statements. These two links might be useful

See the below example

if(condition) {
    if(condition) { //if this evaluates to true, logic1 is executed
        logic1;
    }
    else if(condition) { //if the above condition fails, but this condition satisfies then logic 2 is executed
        logic2;
    }
    else { //if the above 2 conditions fail, you can execute logic3
        logic3;
    }
}