Nested if-else behaviour without braces

后端 未结 4 1329
旧巷少年郎
旧巷少年郎 2020-12-03 14:08

Consider the following unformatted nested if-else Java code

if (condition 1)
if (condition 2)
action 1;
else
action 2;

My ques

相关标签:
4条回答
  • 2020-12-03 14:43

    Block 1 is correct, in if else situations with no brackets the else is linked to the nearest if

    if (condition 1)  
    if (condition 2)
    action 1;
    else
    action 2;
    

    is the same as

    if (condition 1)
        if (condition 2)
        action 1;
        else
        action 2;
    

    also brackets are for the sake of understanding level, and ease. In larger if else statements, having no brackets makes error very common

    0 讨论(0)
  • 2020-12-03 14:43

    Just my 2 cents for a better visual representation.

    Everything inside braces will be completely ignored.

       if (false) {
            if (true)
                System.out.println("1");
            else
                System.out.println("2");
        }
    
    0 讨论(0)
  • 2020-12-03 14:59

    You can try it and find that the else applies to the inner if:

    http://ideone.com/iBorYi

    This is a good reason not to write code like this. It's very hard to read and understand what is happening.

    0 讨论(0)
  • 2020-12-03 15:00

    From the documentation:

    The Java programming language, like C and C++ and many programming languages before them, arbitrarily decrees that an else clause belongs to the innermost if to which it might possibly belong.

    0 讨论(0)
提交回复
热议问题