gpt4 book ai didi

c - 我应该明确定义我的枚举常量的值吗

转载 作者:太空狗 更新时间:2023-10-29 14:53:29 26 4
gpt4 key购买 nike

我之前听说过,如果我没有做一些聪明的事情,比如使用这些值作为位掩码,我应该让编译器选择为枚举常量分配哪些值。如果我只是将枚举值用于更明确的代码文档,如果我没有明确定义所有值,是否会出现任何陷阱?我相信值是按升序分配的。我是否应该定义第一个值以确保每次连续编译的值相同?

最佳答案

来自 C99,第 6.7.2.2p3 节:

The identifiers in an enumerator list are declared as constants that have type int and may appear wherever such are permitted. An enumerator with = defines its enumeration constant as the value of the constant expression. If the first enumerator has no =, the value of its enumeration constant is 0. Each subsequent enumerator with no = defines its enumeration constant as the value of the constant expression obtained by adding 1 to the value of the previous enumeration constant. (The use of enumerators with = may produce enumeration constants with values that duplicate other values in the same enumeration.)

唯一需要为第一个枚举器赋值的情况是您希望它的值不同于0。通常,您不会这样做,因为枚举数通常用于索引数组。

下面是“前一个值加1”的简单例子。

enum {
A,
B,
C = 0,
D,
E
};

int main ()
{
printf("%d\n", A);
printf("%d\n", B);
printf("%d\n", C);
printf("%d\n", D);
printf("%d\n", E);
return 0;
}

上述程序的输出是:

0
1
0
1
2

我能想到的唯一“陷阱”是,如果您希望多个 enum 名称表示相同的值,您应该记住将它们贴在您别名的项目旁边,或者在 enum 列表的底部。我更喜欢后者,这样我可以计算 enum 行来预测 enum 值是什么。

enum {
A,
B,
E,

/* aliases below */
C = A,
D = B
};

否则,枚举器就像一个 int 文字。

关于c - 我应该明确定义我的枚举常量的值吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11398442/

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