else 和 else if 语句

只有当 if 语句被视为 false 时,才可以要求程序执行特定的代码段。为此,我们使用 else 关键字。

if(statement)
{
    // Code to execute if the statement is true.
}
else
{
    // Code to execute if the statement is false.
}

两个代码段永远不会一起执行。第一部分(如果一部分)仅在语句为真时执行,而部分部分(另一部分)仅在语句为假时执行。

如果声明尚未经过验证,也可以询问另一个声明。为此,我们使用 else if 关键词。此语句与常规 if 语句的工作方式完全相同,只是在前一语句被视为 false 时才执行测试。

if(statement)
{
    // Code to execute if the statement is true.
}
else if(another_statement)
{
    // Code to execute if the second statement is true.
}

与以前一样,两个代码永远不会一起执行。如果第一个语句为真,则只会跳过第二个测试,并执行第一部分代码。如果第一个语句为 false,则验证第二个语句,仅当此语句为 true 时才执行第二个语句。

如果需要,可以根据需要添加尽可能多的其他部分以测试不同的语句。如果只有在所有语句都为假的情况下才会执行的部分,也可以在所有其他部分的末尾添加 else 部分。

if(statement)
{
    // Code to execute if the statement is true.
}
else if(second_statement)
{
    // Code to execute if the second statement is true.
}
else if(third_statement)
{
    // Code to execute if the third statement is true.
}
else
{
    // Code to execute if none of the three above statements are true.
}

只执行一个代码段。在验证一个语句时,将跳过以下所有部分,并且不会执行。