if/else 和 if/elseif

if/else and if/elseif

提问人: 提问时间:3/12/2009 最后编辑:sharptooth 更新时间:3/9/2022 访问量:22798

问:

如果我有这样的语句块:

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

或者像这样:

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

有何不同?

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

编程语言 语法 if-statement

评论


答:

2赞 Mehrdad Afshari 3/12/2009 #1

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

0赞 dirkgently 3/12/2009 #2

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

16赞 Frederik Gheysels 3/12/2009 #3

情况一:

if( condition )
{
}
else
{
}

当上述语句中的条件为 false 时,将始终执行 else 块中的语句。

情况 b:

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

当 'condition' 为 false 时,else if 块中的语句将仅在 condition2 为 true 时执行。 当 condition2 为 false 时,将执行 else 块中的语句。

23赞 sharptooth 3/12/2009 #4

如果没有“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
}

这与前一个完全相同,但看起来更好,更容易阅读。

评论

0赞 Romias 3/13/2009
第二种情况...elseif 一个...就像一个开关盒
0赞 sharptooth 3/13/2009
没错,但它被广泛使用,switch 语句不能用于字符串。
0赞 Peter Ajtai 8/5/2010
@sharpooth - 我敢肯定,他们可以在 PHP 和其他方面使用。
0赞 greenoldman 1/28/2015
不对,因为这样的语法是副作用(即它是免费的)。换句话说,没有语法,只有和这里。else ifelse ififelse
0赞 sharptooth 1/28/2015
@greenoldman:是的,你说得对,它是免费的,但是在语言标准术语中,它几乎不是一个“副作用”,它只是一种组织代码的方式。
0赞 DaClown 3/12/2009 #5

你自己已经给出了答案。if/else 表示 true/false 结果,like 是 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 它更易读。

3赞 Gumbo 3/12/2009 #6

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

IfStatement
if ( 表达式 ) 语句 else 语句 if 表达式 语句

语句

VariableStatement EmptyStatement 表达式语句 IfStatement 迭代语句

ContinueStatement BreakStatement ReturnStatement WithStatement LabelledStatement







SwitchStatement ThrowStatement TryStatement


{ StatementListopt
}

StatementList :
语句 StatementList 语句

因此,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;
}
3赞 Sebastian Mach 3/13/2009 #7

强调秋葵说的话。

此外,如果一门语言有一个真正的 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

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赞 Merbin Joe 2/22/2016 #8

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赞 Muhammad Taha Azam 4/2/2017 #9
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);
        }
    }
}
2赞 Sakthivel sockkalingam 4/5/2019 #10
**if/else**
if(condition)
  statement;
else
   statement;

if/ else if /else

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

if/else and if/else if used also like this

0赞 Divishath Reddy Adidala 3/9/2022 #11
// simple if-else statement
if(condition)
{
  statement;
}
else
{
statement;
}

评论

0赞 MD. RAKIB HASAN 3/15/2022
This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review