gpt4 book ai didi

c - C 编译器接受的可疑 case 语句语法

转载 作者:行者123 更新时间:2023-12-02 10:40:38 26 4
gpt4 key购买 nike

我发现一个长期存在的错误是一些代码(我已经编写了代码,所以这是我自己的错)。我无法理解的是为什么编译器没有发现它。
代码是用 C 编写的,我已经使用了很多年,我一直认为自己很了解,但这对我来说没有意义。我在 Visual Studio 和 Gnu C 编译器下都尝试过类似的代码,都接受了。
代码是:

enum TYPE_ENUMS {
TEST_CASE = 1,
};

int main()
{
int caseVal = 1;
switch (caseVal) {
TEST_CASE:
printf("1\n");
default:
printf("Unknown Case %d\n", caseVal);
break;
}
}
任何人都可以解释枚举如何成为 case 语句的一部分,而之前没有“case”。
这应该是有效代码吗?如果是这样,它有什么用处吗?

最佳答案

你所拥有的实际上是一个 标签这可以是 goto 的目标声明,并且没有限制说普通标签不能出现在 switch 中。堵塞。
标签位于与普通标识符不同的命名空间中,包括 enum常数,因此它们可以无歧义地共存。这在 C standard 的第 6.2.3p1 节中有详细说明。 :

If more than one declaration of a particular identifier isvisible at any point in a translation unit, the syntacticcontext disambiguates uses that refer to different entities.Thus, there are separate name spaces for various categories ofidentifiers, as follows:

  • label names (disambiguated by the syntax of the label declaration and use);
  • the tags of structures, unions, and enumerations (disambiguated by following any of the keywords struct, union, or enum);
  • the members of structures or unions; each structure or union has a separate namespace for its members (disambiguated by the typeof the expression used to access the member via the . or ->operator);
  • all other identifiers, called ordinary identifiers(declared in ordinary declarators or as enumeration constants).

关于c - C 编译器接受的可疑 case 语句语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64264898/

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