Albert Renshaw Albert Renshaw - 5 months ago 8
Objective-C Question

Break from an if statement into the else section

I have an if/else statement.

if (something) {
//run if logic
} else {
//run else logic
}


During my
if logic phase
, I may find something that makes me want to run the else portion of my if/else statement instead. The logic phase is too complex to just fit in the initial conditional,
something
.

Is there anything like
break;
that can be used to jump to the
else
portion of an if/else statement.

I'm currently doing this, but I dislike using goto

if (something) {
//run if logic
if (somethingComplex) {
goto elseSomething;
}
} else {
elseSomething:
//run else logic
}


Note again that
somethingElseComplex
is a boolean state achieved by running some complex code too big/multi-lined to fit in my initial if conditional, otherwise I would have just done:
if (something && somethingComplex)
, and if I calculate somethingComplex before the first conditional is called I can get false-positive results. on
!something
values

Answer

I'd use a boolean flag set beforehand, and not use if/else but rather two separate if statements, like this (this is Swift code, but it's the same structure):

var needToDoSomethingElseComplex = false
if something {
    // do stuff
    if somethingComplex {
        needToDoSomethingElseComplex = true
    }
}
if !something || needToDoSomethingElseComplex {
    // do something else complex
}