else 语句遵循什么顺序?

Which order does the else statement follow?

我想确定一些事情,

当我有多个 if/else 条件并且 if 并不意味着其中一个 if 条件的 else 条件;下一个 else 语句是否适用于最后一个 if 语句?

例如:

if(condition1)
{
    //operation1
}

if(condition2)
{
    //operation2
}

else
{
    //operation3.  
}

像上面的例子,如果我不对第一个 if 语句使用 else,那么这个 else 对哪个 if 语句起作用?如果我不为每个 if 指定 else,这会对我造成问题吗?

我做了一些测试,但想确定它实际上是如何工作的。

if i don't use an else for the first if statement, which if statement does this else work for?

第二个 if 语句。
规则是,如果有多个 ifelse 将与最近的 if 一起使用。

C11 §6.8.4.1/3:

An else is associated with the lexically nearest preceding if that is allowed by the syntax.

else 语句绑定到最后一个 if 语句。由于第二个 if 语句

,第一个 if 语句没有 else

else 语句必须始终直接跟在 if 语句(或其块)之后。因此,示例中的 else 会影响 if(condition2)

来自Standard, p 6.8.4.1

An else is associated with the lexically nearest preceding if that is allowed by the syntax.

因此,在您的示例中,else 属于第二个 if(带有 condition2 的那个)。

最近的。如果语法允许,则 else 与词法上最近的前面相关联。

if(condition1)
{
//operation1
}

if(condition2)
{
//operation2
} else {          // <<<<
//operation3.  
}

引用 C11 标准,章节 §6.8.4.1,The if statement强调我的

An else is associated with the lexically nearest preceding if that is allowed by the syntax.

因此,您的 else 语句绑定到 词法上最近的前面 if 语句,这是if(condition2)声明。

'else' 总是附加到最近的 'if'。换句话说,最后一个 else 与最后一个 if.

配对

为了提高可读性最好使用花括号和适当的缩进。

在 C(和其他类似 C 的编程语言)中,您可以放置​​额外的赞誉以使陈述更加清晰。您的代码相当于:

{
    if(condition1) {
        //operation1
    }
}

{
    if(condition2) {
        //operation2
    } else {
        //operation3.  
    }
}

else 语句绑定到第二个 if 语句。这意味着程序将首先计算 condition1。如果 condition1 成立,它将执行 operation1。接下来不管第一个测试的结果如何,都会测试condition2。如果condition2成立,则执行operation2,否则执行operation3。 else 始终与尚未受 else 限制的最近的 if(自下而上)绑定,或者使用大括号作为另一个绑定策略的括号。

else 是最后一个 if that 在 else 之前。

你可以在这里看到更多:http://www.cplusplus.com/doc/tutorial/control

祝你好运!

我不知道你到底想做什么?但您可以使用 if /else if 语句,您可以使用 swtich。

example if-else:

      if(condition 1)
      {
        // your code here
      }
      else if(conditition2)
      {
         //your code here
      } 
      else
      {
        // your code here
       } 

or a swtich:
var caseSwitchLastName = "De Waard"
var caseSwitchFirstName = "Pieter";
switch (caseSwitchFirstName)
{
    case Pieter:
       Console.WriteLine("His name is Pieter");
       break;
    case Sander:
       Console.WriteLine("His name is Sander");
       break;
    default:
       Console.WriteLine("His name is de Waard");
       break;
} 

两个代码的输出相同。只有例子少打字。

共有三种不同类型的选择语句。

单选语句(if)

  • 仅当条件为真时才执行操作

双选语句(if...else)

  • 如果条件为真则执行一个动作,如果条件为假则执行另一个动作

多选语句(切换)

  • 根据常量内部表达式的可能值执行不同的操作

在你的例子中,第一个 if 是单选语句,当它到达块的末尾时 } 它将继续程序中以下语句的顺序处理。

因为你的 else 就在你的第二个 if 之后,因此它使这个语句成为一个双重选择语句。如果结果为真,则执行 if 块中的操作,如果结果为假,则执行 else 中的操作。

总是 else 与其前面的 if 语句相关。