mod*_*ler 99 c++ syntax language-lawyer
我是C++的新手.我经常看到如下条件语句:
if
statement_0;
else if
statement_1;
Run Code Online (Sandbox Code Playgroud)
题:
从语法上讲,我应该将其else if视为单个关键字吗?或者它实际上是如下所示if的外部嵌套语句else?
if
statement_0;
else
if
statement_1;
Run Code Online (Sandbox Code Playgroud)
Sha*_*our 133
如果我们转到草案C++标准部分,它们不是单个关键字.2.12 关键字表4列出了两者if并else单独列出并且没有else if关键字.我们可以通过关键字的cppreferences部分找到更易于访问的C++ 关键字列表.
部分中的语法6.4也清楚地说明了这一点:
selection-statement:
if ( condition ) statement
if ( condition ) statement else statement
Run Code Online (Sandbox Code Playgroud)
该if在else if一个声明中继else项.该部分还说:
[...] selection-statement中的子语句(每个子语句,if语句的 else形式)隐式定义块作用域(3.3).如果selection-statement中的子语句是单个语句而不是复合语句,则就好像它被重写为包含原始子语句的复合语句一样.
并提供以下示例:
if (x)
int i;
can be equivalently rewritten as
if (x) {
int i;
}
Run Code Online (Sandbox Code Playgroud)
那么你的稍微扩展的例子如何被解析?
if
statement_0;
else
if
statement_1;
else
if
statement_2 ;
Run Code Online (Sandbox Code Playgroud)
将被解析如下:
if
{
statement_0;
}
else
{
if
{
statement_1;
}
else
{
if
{
statement_2 ;
}
}
}
Run Code Online (Sandbox Code Playgroud)
注意
我们还else if可以通过认识到关键字是标识符来确定不能是一个关键字,我们可以在语法中看到我的答案中的标识符你能用数字开始一个类名吗?标识符中不允许使用空格,因此else if不能是单个关键字,但必须是两个单独的关键字.
Jam*_*nze 78
从语法上讲,它不是一个单一的关键字; 关键字不能包含空格.逻辑上,写的列表时else
if,它可能会更好,如果你把它看成一个单一的关键字,并且写:
if ( c1 ) {
// ...
} else if ( c2 ) {
// ...
} else if ( c3 ) {
// ...
} else if ( c4 ) {
// ...
} // ...
Run Code Online (Sandbox Code Playgroud)
编译器字面上将其视为:
if ( c1 ) {
// ...
} else {
if ( c2 ) {
// ...
} else {
if ( c3 ) {
// ...
} else {
if ( c4 ) {
// ...
} // ...
}
}
}
Run Code Online (Sandbox Code Playgroud)
但两种形式都是相同的,第一种形式更具可读性.
pab*_*977 24
不它不是.
它们是两个关键字,而且,第二个"if"是由第一个"else"语句确定的范围"内部"的子语句.
rei*_*eer 16
您可以使用花括号来查看范围:
if(X) {
statement_0;
}
else {
if(Y) {
statement_1;
}
}
Run Code Online (Sandbox Code Playgroud)
通常使用两个不同的关键字实现,一个是if,另一个是else.
The*_*ask 10
如已经回答的那样,事实并非如此.它们是两个关键词.这是两个跟随彼此的两个陈述的开始.为了让它更清楚一点,这里是用C++语言处理if和else语句的BNF gramar .
statement:
labeled-statement
attribute-specifier-seqopt expression-statement
attribute-specifier-seqopt compound-statement
attribute-specifier-seqopt selection-statement
attribute-specifier-seqopt iteration-statement
attribute-specifier-seqopt jump-statement
declaration-statement
attribute-specifier-seqopt try-block
selection-statement:
if ( condition ) statement
if ( condition ) statement else statement
Run Code Online (Sandbox Code Playgroud)
请注意,statement它本身包括selection-statement.所以,组合如:
if (cond1)
stat
else if(cond2)
stat
else
stat
Run Code Online (Sandbox Code Playgroud)
根据C++标准/语义是可行和有效的.
注意:C++语法来自此页面.
| 归档时间: |
|
| 查看次数: |
9623 次 |
| 最近记录: |