JAVA BNF “no short if” - what does this mean?

瘦欲@ 提交于 2019-12-13 05:36:45

问题


Basically the title. Looking through the Java BNF, I see "no short if" such as in:

<statement no short if> ::= <statement without trailing substatement> | <labeled statement no short if> | <if then else statement no short if> | <while statement no short if> | <for statement no short if>

What does it "no short if" mean? I see "NoShortIf" popping up in my lecture slides with no explanation of what it means.


回答1:


The answer is in the link provided above in the comment by @Andy Turner:

Statements are thus grammatically divided into two categories: those that might end in an if statement that has no else clause (a "short if statement") and those that definitely do not.

Only statements that definitely do not end in a short if statement may appear as an immediate substatement before the keyword else in an if statement that does have an else clause.

This simple rule prevents the "dangling else" problem. The execution behavior of a statement with the "no short if" restriction is identical to the execution behavior of the same kind of statement without the "no short if" restriction; the distinction is drawn purely to resolve the syntactic difficulty.




回答2:


A "short if" is an if statement without an else.

"Short ifs" are not allowed in certain situations to eliminate ambiguity.

The following is valid Java. There are no "short ifs" and no ambiguity.

boolean flag = false;
if (x > 0) 
    if (x > 10)
        flag = true;
    else
        flag = false;
else 
    flag = true;

The following is also valid java code, but without the "short if" rules there is ambiguity as to which if the else belongs.

if (x > 0)  if (x < 10) flag = true; else  flag = false;

The following Java language rules

IfThenStatement:
   if ( Expression ) Statement
IfThenElseStatement:
   if ( Expression ) StatementNoShortIf else Statement

imply that the meaning of the above code is

if (x > 0)  
    if (x < 10) 
       flag = true; 
    else  
       flag = false;

That is, the else belongs to the inner if statement.

Let's test in Java to be sure

static Boolean shorty (int x) {
    Boolean flag = null;
    if (x > 0)  if (x < 10) flag = true; else  flag = false;
    return flag;
}


public static void main(String[] args) {
    System.out.println(shorty(-1));
    System.out.println(shorty(5));
    System.out.println(shorty(20));
}

The output is

null
true
false


来源:https://stackoverflow.com/questions/36048981/java-bnf-no-short-if-what-does-this-mean

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!