为什么 "case::LABEL:" 在 g++ 中编译?
Why does "case::LABEL:" compile in g++?
得知 g++ (4.9) 正在编译它(而 gcc 不会),我感到很惊讶:
#include <stdio.h>
enum
{
ONE = 1,
TWO = 2,
THREE = 3
};
int main(int argc, char* argv[])
{
int sw = 2;
switch (sw)
{
case::ONE:
{
printf("1\n");
break;
}
case::TWO:
{
printf("2\n");
break;
}
case::THREE:
{
printf("3\n");
break;
}
default:
{
printf("default\n");
}
}
}
g++ 预处理器如何能够将 "case" 与“::ONE:”分开?
它不是预处理器。 C 编译器(它的分词器)将其视为:
case :: ONE
这在 C++ 中是可以的。 :: 运算符表示根命名空间。 C没有这样的东西。
How is the g++ preprocessor able to separate the "case" from the "::ONE:"?
不是预处理器,而是编译器,将 ::
解释为引用全局命名空间。
案例标签将被解析为
case :: THREE :
这完全没问题,因为您的 enum
值出现在全局命名空间 (::
) 中。
您有一个简单的枚举,而不是范围内的枚举(参见:enum class
)。普通枚举在根范围内,因此你可以写 ::ONE
.
使用范围枚举,您可以执行以下操作:
enum class Scoped { FIRST, LAST = 9};
//...
case Scoped::FIRST : //...
即使您不在 case
关键字和枚举数之间留空格,g++ 中的分词器(因为这是一个 C++ 功能)也可以解析。
在 lexical analysis phase of the compilation process, the stream of characters in the program file is converted to tokens. One of the popular algorithms used here is maximal munch 期间,最长的匹配合法令牌被视为预期令牌。在此示例中,它将 case::ONE:
拆分为 case
、::
、ONE
和 :
。
也有一些缺点:x = y/*z
是一个错误,因为 /*
是最长的匹配合法标记,而用户可能想说 x = y / *z
。你可以找到很多这样奇怪的例子,其中几个是 here and here.
得知 g++ (4.9) 正在编译它(而 gcc 不会),我感到很惊讶:
#include <stdio.h>
enum
{
ONE = 1,
TWO = 2,
THREE = 3
};
int main(int argc, char* argv[])
{
int sw = 2;
switch (sw)
{
case::ONE:
{
printf("1\n");
break;
}
case::TWO:
{
printf("2\n");
break;
}
case::THREE:
{
printf("3\n");
break;
}
default:
{
printf("default\n");
}
}
}
g++ 预处理器如何能够将 "case" 与“::ONE:”分开?
它不是预处理器。 C 编译器(它的分词器)将其视为:
case :: ONE
这在 C++ 中是可以的。 :: 运算符表示根命名空间。 C没有这样的东西。
How is the g++ preprocessor able to separate the "case" from the "::ONE:"?
不是预处理器,而是编译器,将 ::
解释为引用全局命名空间。
案例标签将被解析为
case :: THREE :
这完全没问题,因为您的 enum
值出现在全局命名空间 (::
) 中。
您有一个简单的枚举,而不是范围内的枚举(参见:enum class
)。普通枚举在根范围内,因此你可以写 ::ONE
.
使用范围枚举,您可以执行以下操作:
enum class Scoped { FIRST, LAST = 9};
//...
case Scoped::FIRST : //...
即使您不在 case
关键字和枚举数之间留空格,g++ 中的分词器(因为这是一个 C++ 功能)也可以解析。
在 lexical analysis phase of the compilation process, the stream of characters in the program file is converted to tokens. One of the popular algorithms used here is maximal munch 期间,最长的匹配合法令牌被视为预期令牌。在此示例中,它将 case::ONE:
拆分为 case
、::
、ONE
和 :
。
也有一些缺点:x = y/*z
是一个错误,因为 /*
是最长的匹配合法标记,而用户可能想说 x = y / *z
。你可以找到很多这样奇怪的例子,其中几个是 here and here.