if/else and if/elseif

后端 未结 10 1872
傲寒
傲寒 2020-12-17 01:00

If I have a statement block like this:

if (/*condition here*/){ }
else{ }

or like this:

if (/*condition here*/)
else if (/         


        
10条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-17 01:49

    Emphasizing what Gumbo said.

    Also, if a language has a real elif / elsif / elseif (say, a "real" else-if instruction, instead of a kind of nested chaining hidden away by formatting), then the compiler can easly emit a single node in an Abstract Syntax Tree (or similar, see http://en.wikipedia.org/wiki/Abstract_syntax_tree) instead of nesting them.

    To give an example:

    Say in C/C++ you have:

    if (a) {
        X
    } else if (b) {
        Y
    } else if (c) {
        Z
    } else {
        0
    }
    

    Then the compiler will build an AST-node like this:

       a
      / \
     X   b
        / \
       Y   c
          / \
         Z   0
    

    But if the language of choice has a real if-else:

    if (a) {
        X
    } elif (b) {
        Y
    } elif (c) {
        Z
    } else {
        0
    }
    

    Then the AST could more easily look like this:

       (a--b--c)
       /  /  /  \
      X  Y  Z    0
    

    In such a language, an "if else" would only be possible if braces are not mandatory:

    if (a) {
        X
    } elif (b) {
        Y
    } else if (c) {  // syntax error "missing braces" if braces mandatory
        Z
    } else {
        0
    }
    

    Corresponding AST (if braces are not mandatory):

       (a--b)
       /  /  \
      X  Y    c
             / \
            Z   0
    

    This could make CFG-Analysis (http://en.wikipedia.org/wiki/Control_flow_graph) easier to implement (though there might be no actual optimization benefit; so imho it'd just benefit the lazy programmer :D).

提交回复
热议问题