【问题标题】:if/else and if/elseifif/else 和 if/elseif
【发布时间】:2010-10-12 21:15:06
【问题描述】:

如果我有这样的语句块:

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

或者像这样:

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

有什么区别?

似乎在 if/else 中,if 部分用于 true 状态,else 部分用于所有其他可能的选项(false)。 else-if 对许多条件很有用。这是我的理解,还有什么需要注意的吗?

【问题讨论】:

    标签: programming-languages syntax if-statement


    【解决方案1】:

    如果没有“elseif”语法,您将不得不编写链式 if 语句来以这种方式处理几种可能的结果之一:

    if( str == "string1" ) {
       //handle first case
    } else {
        if( str == "string2" ) {
           //handle second case
        } else {
           if( str == "string3" ) {
               //handle third case
           } else {
              //default case
           }
        }
     }
    

    你可以写

    if( str == "string1" ) {
       //handle first case
    } else if( str == "string2" ) {
       //handle second case
    } else if( str == "string3" ) {
       //handle third case
    } else {
       //default case
    }
    

    和上一个完全一样,但是看起来更漂亮,更容易阅读。

    【讨论】:

    • 第二种情况... elseif 那个... 就像一个Switch Case
    • 没错,但它被广泛使用,switch语句不能用于字符串。
    • @sharpooth - 他们可以在 PHP 和其他我确定。
    • 不正确,因为使用这种语法 else if 是副作用(即它是免费的)。也就是说没有else if语法,这里只有ifelse
    • @greenoldman:是的,你说得对,它是免费的,但在语言标准术语中它几乎不是“副作用”,它只是一种组织代码的方式。
    【解决方案2】:

    情况一:

    if( condition )
    {
    }
    else
    {
    }
    

    当上述语句中的条件为假时,else块中的语句将一直被执行。

    情况乙:

    if( condition )
    {
    }
    else if( condition2 )
    {
    }
    else
    {
    }
    

    当 'condition' 为 false 时,else if 块中的语句只会在 condition2 为 true 时执行。 当条件2为假时,将执行else块中的语句。

    【讨论】:

      【解决方案3】:

      许多语言都有这样的语法(这里:ECMAScript Language Specification,所以是 JavaScript):

      IfStatement :
      if ( 表达 ) 声明 else 声明
      if ( 表达 ) 声明

      声明 :
      阻止
      变量声明
      EmptyStatement
      表达式语句
      If 语句
      迭代语句
      继续声明
      BreakStatement
      退货声明
      WithStatement
      标签声明
      SwitchStatement
      ThrowStatement
      TryStatement

      阻止
      { StatementListopt}

      声明列表 :
      声明
      声明列表 声明

      因此,ifStatement 的分支可能包含一个语句块(Block)或其他语句之一(Block 除外) .这意味着这是有效的:

      if (expr)
          someStatement;
      else
          otherStatement;
      

      并且由于StatementList可能只包含一个语句,这些例子与前面的例子是等价的:

      if (expr) {
          someStatement;
      } else {
          otherStatement;
      }
      
      if (expr)
          someStatement;
      else {
          otherStatement;
      }
      
      if (expr) {
          someStatement;
      } else
          otherStatement;
      

      当我们用一个额外的 IfStatement 替换 otherStatement 时,我们得到:

      if (expr) {
          someStatement;
      } else
          if (expr) {
              someOtherStatement;
          }
      

      剩下的只是代码格式化:

      if (expr) {
          someStatement;
      } else if (expr) {
          someOtherStatement;
      }
      

      【讨论】:

        【解决方案4】:

        强调秋葵所说的。

        另外,如果一种语言有一个真正的 elif / elsif / elseif(比如说,一个“真正的” else-if 指令,而不是一种通过格式化隐藏起来的嵌套链接),那么编译器可以轻松地发出单个节点在抽象语法树(或类似的,请参阅http://en.wikipedia.org/wiki/Abstract_syntax_tree)中,而不是嵌套它们。

        举个例子:

        用 C/C++ 说你有:

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

        然后编译器将像这样构建一个 AST 节点:

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

        但是如果选择的语言有一个真正的 if-else:

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

        那么 AST 可以更容易地看起来像这样:

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

        在这种语言中,“if else”只有在大括号不是强制性的情况下才有可能:

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

        对应的AST(如果大括号不是强制性的):

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

        这可以使 CFG 分析 (http://en.wikipedia.org/wiki/Control_flow_graph) 更容易实现(尽管可能没有实际的优化好处;所以恕我直言,它只会让懒惰的程序员受益:D)。

        【讨论】:

          【解决方案5】:

          else if 基本上意味着ifelse 部分是另一个if 语句。

          【讨论】:

            【解决方案6】:
            **if/else**
            if(condition)
              statement;
            else
               statement;
            

            如果/否则如果/否则

            if(condition)
             {
               if(condition)
                  statement;
               else 
                 statement;
              }   
            else if(condition)
            {
                if(condition)
                 statement;
                else
                 statement;
            }
            else
                statement;
            

            if/else 和 if/else if 也这样使用

            【讨论】:

              【解决方案7】:

              给定一个变量,您将使用简单的if-else 结构。当有多个变量并且您有不同的路径来执行不同的可能性时,您将使用if-else if-...-else。请注意,后者也以 else 语句结尾。

              【讨论】:

                【解决方案8】:

                你自己已经给出了答案。 if/else 用于真/假结果,如 int=2 或任何其他可能的 int 值,if/elseif 用于超过 2 个结果,如 int=2 和 int=3 等等。

                它还对变量的上下文进行分组。您可以检查每个结果,例如

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

                使用 if/else/elseif 可读性更好。

                【讨论】:

                  【解决方案9】:

                  如果您想检查更多条件,我们可以使用 if..elseif。单一条件,那么我们可以使用 if 或 if...else。

                  在这里我无法上传完整的示例说明,因此请通过以下链接。

                  if..else 语句详细信息
                  http://allinworld99.blogspot.in/2016/02/ifelse-flow-chart-with-easy-example.html
                  if...elseif 详细信息
                  http://allinworld99.blogspot.in/2016/02/flow-chart-with-example-for-if-then.html

                  【讨论】:

                    【解决方案10】:
                    import java.util.*;
                    
                    public class JavaApplication21 {
                        public static void main(String[] args) {
                    
                            Scanner obj = new Scanner(System.in);
                            System.out.println("You are watching an example of if & else if statements");
                    
                            int choice, a, b, c, d;
                            System.out.println(" Enter 1-Addition & 2-Substraction");
                    
                            int option = obj.nextInt();
                            switch (option) {
                                case (1):
                                    System.out.println("how many numbers you want to add.... it can add up to 3 numbers only");
                                    choice = obj.nextInt();
                                    if (choice == 2) {
                                        System.out.println("Enter 1st number");
                                        a = obj.nextInt();
                    
                                        System.out.println("Enter 2nd number");
                                        b = obj.nextInt();
                    
                                        c = a + b;
                    
                                        System.out.println("Answer of adding " + a + " & " + b + " is= " + c);
                                    } else if (choice == 3) {
                                        System.out.println("Enter 1st number");
                                        a = obj.nextInt();
                    
                                        System.out.println("Enter 2nd number");
                                        b = obj.nextInt();
                    
                                        System.out.println("Enter 3rd number");
                                        c = obj.nextInt();
                    
                                        d = a + b + c;
                    
                                        System.out.println("Answer of adding " + a + " , " + b + " & " + c + "  is= " + d);
                                    }
                                case (2):
                                    System.out.println("how many numbers you want to substract.... it can substract up to 3 numbers only");
                                    choice = obj.nextInt();
                                    if (choice == 2) {
                                        System.out.println("Enter 1st number");
                                        a = obj.nextInt();
                    
                                        System.out.println("Enter 2nd number");
                                        b = obj.nextInt();
                    
                                        c = a - b;
                                        System.out.println("Answer of substracting " + a + " & " + b + " is= " + c);
                                    } else if (choice == 3) {
                                        System.out.println("Enter 1st number");
                                        a = obj.nextInt();
                    
                                        System.out.println("Enter 2nd number");
                                        b = obj.nextInt();
                    
                                        System.out.println("Enter 3rd number");
                                        c = obj.nextInt();
                    
                                        d = a - b - c;
                                        System.out.println("Answer of substracting " + a + " , " + b + " & " + c + "  is= " + d);
                                    }
                                default:
                                    System.out.println("no option you have chosen" + option);
                            }
                        }
                    }
                    

                    【讨论】:

                      猜你喜欢
                      • 1970-01-01
                      • 2016-11-21
                      • 1970-01-01
                      • 2020-08-14
                      • 1970-01-01
                      • 2023-04-05
                      • 2021-07-11
                      • 2021-01-03
                      • 1970-01-01
                      相关资源
                      最近更新 更多