gpt4 book ai didi

c - 与枚举器同名的变量

转载 作者:太空狗 更新时间:2023-10-29 17:09:18 28 4
gpt4 key购买 nike

像下面这样的定义的行为是什么?

#include <stdio.h>

typedef enum {
ENUM_VAL_1 = 1,
ENUM_VAL_2 = 2
} TEST_ENUM;

int main() {
TEST_ENUM testVar1 = ENUM_VAL_1;
TEST_ENUM ENUM_VAL_1 = ENUM_VAL_1;
TEST_ENUM testVar2 = ENUM_VAL_1;

printf("ENUM_VAL_1 = %u\n",ENUM_VAL_1);
printf("testVar1 = %u\n",testVar1);
printf("testVar2 = %u\n",testVar2);

return 0;
}

根据我对 GCC 和 MSVC 编译器的测试,其行为是 testVar1 将设置为等于枚举值“ENUM_VAL_1”或 1。但是,下一条语句将尝试将变量 ENUM_VAL_1 设置为其自身值,这当然是当前未初始化的,因此是垃圾,而不是将变量 ENUM_VAL_1 设置为等于枚举值 ENUM_VAL_1。然后,当然,testVar2 也会得到与变量 ENUM_VAL_1 相同的垃圾值。

根据 C 标准,this 的定义行为是什么,或者这是未定义的行为?不管它是否被定义,我猜这种类型的例子至少是因为含糊不清是不好的做法。

谢谢!

最佳答案

根据C标准(6.2.1标识符的范围)

  1. ... If an identifier designates two different entities in the same name space, the scopes might overlap. If so, the scope of one entity (the inner scope) will end strictly before the scope of the other entity (the outer scope). Within the inner scope, the identifier designates the entity declared in the inner scope; the entity declared in the outer scope is hidden (and not visible) within the inner scope.

7 Structure, union, and enumeration tags have scope that begins just after the appearance of the tag in a type specifier that declares the tag. Each enumeration constant has scope that begins just after the appearance of its defining enumerator in an enumerator list. Any other identifier has scope that begins just after the completion of its declarator

所以在这个声明中

TEST_ENUM ENUM_VAL_1 = ENUM_VAL_1;

声明符 ENUM_VAL_1 在符号 = 之前被视为已完成。所以它隐藏了枚举器。

实际上它是自己初始化的,有一个不确定的值。

同样适用于C++(3.3.2声明点)

1 The point of declaration for a name is immediately after its complete declarator (Clause 8) and before its initializer (if any), except as noted below. [ Example:

int x = 12;
{ int x = x; }

Here the second x is initialized with its own (indeterminate) value. —end example ]

关于c - 与枚举器同名的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27827670/

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