简体   繁体   中英

Can if statements be broken half way through?

I was just wondering if an 'if' statement that is halfway through running will stop running if the conditions it has to meet are no longer met. It is hard to explain with words, here is an example:

boolean flag = true;

if(flag){

//Some code execution here (code execution #1)

flag = false;

//Some more code execution here (code execution #2)


}

Will the "code execution #2" run in this case? Or will the the rest of the if statement be skipped when flag is set to false?

由于条件检查时标志等于true,因此将执行if语句的全部内容。

Definitely not in the case that you describe, since the condition in the if statemet is evaluated at the time that the if is executed.

if you need a program flow control mechanism to break out of a if statement you can use exceptions (but this is less than ideal for a lot of reasons, )

Alternatively you can use a label and a break statement:

    boolean flag = false;
    MYLABEL:
    if (flag) {
        if (true) {
            break MYLABEL;
        }
        System.err.println("I will not execute");
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM