是否存在 else if 语句?

Does an else if statement exist?

前段时间站不起来后这样的台词:

if (arg)
    invk(test);
else if (test)
{
    alot();
    stuff();
}

我自己决定在 1920x1200 时代的可读性更好,不要省略 {}

所以我写了一个工具来重新格式化我现有的代码。

后来我注意到该工具中的一个错误导致

if (x)
{
 ...
}
else if(y)
{
 ...
}
else if(z)
{
 ...
}

已更改(未明显更改行为)为:

if (x)
{
 ...
}
else 
{
    if(y)
    {
     ...
    }
    else
    {
        if(z)
        {
         ...
        }
    }
}

这让我意识到(无意中)这实际上是 else if 根据 C 的语法和语义规则所做的事情。

那么是否存在像 else if() 这样的语句,或者它只是滥用语义导致了这个有用的但是(为此目的我们这样称呼它)混淆起源的措辞打破了任何格式规则和只是作为人类可读的?

根据C11,第 6.8.4 章,选择语句,可用的语句块是

if ( expression ) statement
if ( expression ) statement else statement
switch ( expression ) statement

并且,关于 else 部分,

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

因此,没有 else if 结构,按照标准 C 存在。

显然,if(或if...else)块可以作为语句存在于else块中(嵌套if...else,我们可能会说)。

缩进的选择留给用户。


注:

补充一下,没有理由单独存在else if构造,功能可以通过嵌套来实现。参见 this wiki article。相关引用

The often-encountered else if in the C family of languages, and in COBOL and Haskell, is not a language feature but a set of nested and independent "if then else" statements combined with a particular source code layout. However, this also means that a distinct else-if construct is not really needed in these languages.

众所周知,有几种不同风格的编程语言。 elseif 的存在基于语言风格。 在 C/Pascal 样式中,if 语句是

if (...)
   statment; 
else
   statement;

你有一个复合语句: { 声明; 声明; }

在 Modula2 / VB / (python ?) 风格的语言中你有

if (...)
   statement;
   ...
   statement;
else
   statement;
   ...
   statement;
end-if

在 Modula2 / VB 你 需要 一个 elseif 语句因为如果你尝试使用 else如果 你得到

if (..)
else if (..)
else if (..)
end-if; end-if; end-if;

末尾的end-if比较难看。

正如@anatolyg 指出的,这就是为什么您在 C 宏语言中有一个#elif。


Cobol-85 对 elseif 语句有不同的看法。它提供了扩展的 Select/case 语句。在 Cobol 中你有一个评估:

evaluate option
   when 1
      ...
   when 2
      ...

但你也可以做到

evaluate true
   when age > 21 and gender = 'male'
      ...
   when age > 21 and gender = 'female'

在 Cobol 中你也可以混合大小写和 if 结构

evaluate option also true
   when 1 also age > 21 and gender = 'male'
      .... 
   when 1 also age > 21 and gender = 'female'
      .... 
   when 2 also any
      ....

java 和 C 中的最后一点你有时会看到

if () {

} else if () {

} else if () {

}

就所有意图和目的而言,这是用 Java/C 编写的 VB / Modula-2。