【问题标题】:Where does the C standard define the else if statement?C 标准在哪里定义 else if 语句?
【发布时间】:2020-08-27 17:54:08
【问题描述】:

我只是对 C 中的 else if 语句感到好奇,所以我查看了 C99 标准,但一无所获。然后我查看了语法,但又没有else if

selection_statement
    : IF '(' expression ')' statement
    | IF '(' expression ')' statement ELSE statement
    | SWITCH '(' expression ')' statement
    ;

else if 是如何在 C 中声明的。通过阅读标准,我怎么能注意到它是它的一部分?

【问题讨论】:

  • IF '(' expression ')' statement ELSE statement 中的最后一个statement 可以是另一个if 语句。
  • else ifif 语句作为语句的副产品。
  • 澄清一下,ifelse 之后并没有什么特别之处。这只是另一种说法。
  • 在 C18 第 6.8.4 节 选择语句
  • @WeatherVane 可以下载 C18 吗?

标签: c if-statement c99


【解决方案1】:

C 2018 6.8.4 说 selection-statement 可能是“if ( 表达式 ) statement else 声明”。 C 2018 6.8 表示后一个 statement 可能是“selection-statement”,因此它可能是 ifif … else 语句,这会导致包含以下内容的语句else if.

【讨论】:

  • 在控制流结构的子句必须是块的语言中,这可能会有所不同。没有人愿意编写像 if (expression) { statements; } else { if (expression2) { statements; } else { if (expression3) { statements; } else { ... } } } 这样的长 if-else 链。
【解决方案2】:

else if 语句在 C18 §6.8.4/1 中通过声明语法被正式定义为 if 语句的副产品:

语法

1 个选择语句:

if ( expression ) statement

if ( expression ) statement else statement

来源:C18,§6.8.4/1

后一种形式的最后一个“语句”描述了在else 之后可以跟随另一个if 语句。


除此之外,您还可以在 G.5.1/8 的代码示例中的规范性附录 G 中找到其在 C 标准中使用的当然非规范性示例:

if (isnan(x) && isnan(y)) { ... }
else if ((isinf(a) ||isinf(b)) && isfinite(c) && isfinite(d)) { ... }
else if ((logbw == INFINITY) && isfinite(a) && isfinite(b)) { ... } 

这是在 C18 标准中出现else if 语句的唯一位置。

所以关于:

通过阅读标准,我如何能注意到它是其中的一部分?

至少虽然示例是非规范性的,但它是其中的一部分。

【讨论】: