gpt4 book ai didi

c - 以下关于 C 编程中枚举的含义是什么?

转载 作者:行者123 更新时间:2023-12-05 09:29:58 25 4
gpt4 key购买 nike

在我正在阅读的一本书中,在数组之前介绍了枚举常量。仅通过几个示例演示了数组的使用。声明如下:

enum corvid { magpie, raven, jay, corvid_num};

char const * const bird [ corvid_num ] =
{
[raven] = "raven",
[magpie] = "magpie",
[jay] = "jay",
};

for ( unsigned i = 0; i < corvid_num ; ++i)
printf ("Corvid %u is the %s\n", i, bird[i]);

This declares a new integer type enum corvid for which we know four different values.

Takeaway - Enumeration constants have either an explicit or a positional value

As you might have guessed, positional values start from 0 onward, so in our examplewe have raven with value 0, magpie with 1, jay with 2, and corvid_num with 3. This last3 is obviously the 3 we are interested in.

问题一:

[magpie] = "magpie" 是否表示 magpie 位置引用值 "magpie"

问题二:

根据循环,bird[0] 如何等于 "raven" ,因为这是明确的而不是位置值。同样在第一次迭代之后 [i + 1] 将等于 [magpie]。总之,为什么循环变量的类型是无符号的而不是 corvid 或枚举 corvid?

我想我误解了枚举常量。

也来自,

As you might have guessed, positional values start from 0 onward, so in our example we have raven with value 0, magpie with 1, jay with 2, and corvid_num with 3. This last 3 is obviously the 3 we are interested in.

作者说 raven 的值应该为 0 而不是 magpie 是否正确,如果这是一个错字,我的所有困惑都会消除。

最佳答案

在声明 char const * const bird [ corvid_num ] [ ] 之间的项目是数组的大小。在初始化器列表中,[ raven ] = "raven "[ ] 之间的项是所谓的指定初始化器,用于初始化数组中的特定项目。

Question 1 : Does ' [ magpie ] = " magpie "' imply that 'magpie'TH position refers to value "magpie".

是的。

Question 2 : According to loop, how is bird [0] equal to "raven" , since this is explicit and not a positional value.

因为枚举是命名常量。如果枚举常量(raven 等)未明确给出一个数字,则会隐式给出一个数字,从 0 开始。raven 在您的示例中是第二项枚举,因此它的值为 1,每当您在源代码中键入 raven 时,它将等同于键入 1

As you might have guessed, positional values start from 0 onward, so in our example we have raven with value 0, magpie with 1, jay with 2, and corvid_num with 3. This last 3 is obviously the 3 we are interested in.

这是 Gustedt - Modern C 中的一个错误。可能存在勘误表?示例代码的输出是:

Corvid 0 is the magpie
Corvid 1 is the raven
Corvid 2 is the jay

值得注意的是,如果我们没有使用指定的初始值设定项但只是这样做了:

char const * const bird [ corvid_num ] = 
{
"raven",
"magpie",
"jay",
};

那么输出会变成

Corvid 0 is the raven
Corvid 1 is the magpie
Corvid 2 is the jay

关于c - 以下关于 C 编程中枚举的含义是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70165988/

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