是否为"else if"一个关键字? [英] Is "else if" a single keyword?

查看:201
本文介绍了是否为"else if"一个关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C ++的新手.我经常看到如下条件语句:

I am new to C++. I often see conditional statement like below:

if 
  statement_0;
else if
  statement_1;

问题:

从语法上,我应该将else if视为单个关键字吗?还是实际上是外部else中的嵌套if语句,如下所示?

Syntactically, shall I treat else if as a single keyword? Or is it actually an nested if statement within the outer else like below?

if 
  statement_0;
else 
  if
    statement_1;

推荐答案

如果我们转到 cppreferences部分,我们可以找到更易于访问的C ++ 关键字列表.在关键字上.

They are not a single keyword if we go to the draft C++ standard section 2.12 Keywords table 4 lists both if and else separately and there is no else if keyword. We can find a more accessible list of C++ keywords by going to cppreferences section on keywords.

6.4部分中的语法也清楚了这一点:

The grammar in section 6.4 also makes this clear:

selection-statement:
 if ( condition ) statement
 if ( condition ) statement else statement

else if中的if是紧随else术语的声明.该部分还说:

The if in else if is a statement following the else term. The section also says:

[...] 选择声明中的子声明(每个子声明在 if 语句的 else 形式隐式定义了块作用域(3.3). 如果选择语句中的子语句是单个语句,并且 不是复合语句,就好像它被重写为 包含原始子陈述的复合陈述.

[...]The substatement in a selection-statement (each substatement, in the else form of the if statement) implicitly defines a block scope (3.3). If the substatement in a selection-statement is a single statement and not a compound-statement, it is as if it was rewritten to be a compound-statement containing the original substatement.

并提供以下示例:

if (x)
 int i;

can be equivalently rewritten as

if (x) {  
  int i;
}

那么如何解析您稍加扩展的示例?

if 
  statement_0;
else 
  if
    statement_1;
  else
    if
      statement_2 ;

将被这样解析:

if 
{
  statement_0;
}
else
{ 
    if
    {
      statement_1;
    }
    else
    {
        if
        {
         statement_2 ;
        }
    }
}

注意

我们还可以通过意识到关键字标识符来确定else if不能是一个关键字,并且可以从语法中从标识符中看出标识符您可以用数字开头的类名吗?标识符中不允许使用空格,并且因此,else if不能是单个关键字,而必须是两个单独的关键字.

We can also determine that else if can not be one keyword by realizing that keywords are identifiers and we can see from the grammar for an identifier in my answer to Can you start a class name with a numeric digit? that spaces are not allowed in identifiers and so therefore else if can not be a single keyword but must be two separate keywords.

这篇关于是否为"else if"一个关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆