Hanging else problem?

后端 未结 4 1159
轮回少年
轮回少年 2021-01-14 03:12

What is the \"hanging else\" problem? (Is that the right name?)

Following a C++ coding standard (forgot which one) I always use brackets (block) with control structu

相关标签:
4条回答
  • 2021-01-14 03:19

    Ambiguous else.

    Some info here: http://theory.stanford.edu/~amitp/yapps/yapps-doc/node3.html

    But the classic example is:

    if a then
      if b then
         x = 1;
      else 
         y = 1;
    

    vs.

    if a then
      if b then
         x = 1;
    else 
      y = 1;
    
    0 讨论(0)
  • 2021-01-14 03:25

    Looking at this from a langauge design point of view.

    The standard BNF-like grammar for if-else:

    Statement :-   .. STUFF..
              |    IfStatement
    
    IfStatement :- IF_TOKEN '(' BoolExpression ')' Statement IfElseOpt
    
    IfElseOpt :-   /* Empty */
              |    ELSE_TOKEN Statement
    

    Now from a parsers point of view:

    if (cond1) Statement1
       if (cond2) Statement2
    else Statement3
    

    When you get to the ELSE_TOKEN the parser has two options, SHIFT or REDUCE. The problem is that which to choose requires another rule that the parser must follow. Most parsers generators default to SHIFT when given this option.

    0 讨论(0)
  • 2021-01-14 03:37

    Which if does the else belong to?

    if (a < b)
        if (c < d)
            a = b + d;
        else
            b = a + c;
    

    (Obviously you should ignore the indentation.)

    That's the "hanging else problem".

    C/C++ gets rid of the ambiguity by having a rule that says you can't have an-if-without-an-else as the if-body of an-if-with-an-else.

    0 讨论(0)
  • 2021-01-14 03:37

    I don't see the problem for Pascal?

    This one is incorrectly indented.

    if a then
      if b then
         x = 1;
      else
         y = 1;
    

    Removing the semi-colon from after x = 1 would make it correctly indented.

    This one correctly indented

    if a then
      if b then
         x = 1;
    else
      y = 1;
    
    0 讨论(0)
提交回复
热议问题