gpt4 book ai didi

c - 是否存在 else if 语句?

转载 作者:太空狗 更新时间:2023-10-29 16:40:35 25 4
gpt4 key购买 nike

前段时间站不起来之后是这样的:

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,选择语句,可用的语句 block 是

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) block 可以作为 语句 存在于 else block (嵌套 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.

关于c - 是否存在 else if 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37024948/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com