if/else and if/elseif

后端 未结 10 1852
傲寒
傲寒 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:45

    if you want to check more condition we can use if..elseif. single condition then we can use if or if...else.

    Here I can't able to upload the full explanation with example so please go through the following links.

    if..else statement details
    http://allinworld99.blogspot.in/2016/02/ifelse-flow-chart-with-easy-example.html
    if...elseif details
    http://allinworld99.blogspot.in/2016/02/flow-chart-with-example-for-if-then.html

    0 讨论(0)
  • 2020-12-17 01:46

    else if basically means the else part of if is another if statement.

    0 讨论(0)
  • 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).

    0 讨论(0)
  • 2020-12-17 01:49

    You already gave the answer yourself. if/else is for true/false result, like is an int=2 or any other possible int value, and if/elseif is for more than 2 results, like an int=2, and int=3 and so on.

    Also it groups the context of a variable. You could check every single result like

    if (a == 2) { do one thing };
    if (a == 3) { do another thing };
    ...
    if (a != 2 && a != 3 ...) { do something else };
    

    With if/else/elseif it's better readable.

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