![](/img/trans.png)
[英]What does the following mean with respect to, bitwise operations in C programming?
[英]What does the following mean with respect to enumerations in C programming?
在我正在阅读的一本书中,在 arrays 之前已经介绍了枚举常量。 仅通过几个示例演示了 arrays 的使用。 声明如下:
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]);
这声明了一个新的 integer 类型枚举 corvid,我们知道它有四个不同的值。
要点 - 枚举常量具有显式值或位置值
正如您可能已经猜到的,位置值从 0 开始,所以在我们的示例中,我们将 raven 设置为 0,magpie 设置为 1,jay 设置为 2,corvid_num 设置为 3。最后的 3 显然是我们感兴趣的 3。
问题一:
[magpie] = "magpie"
是否暗示magpie
th position 指的是值"magpie"
。
问题2:
根据循环, bird[0]
如何等于"raven"
,因为这是明确的而不是位置值。 同样在第一次迭代之后[i + 1]
将等于[magpie]
。 总而言之,为什么循环变量的类型是无符号的而不是 corvid 或 enum corvid?
我想我误解了枚举常量。
也来自,
正如您可能已经猜到的,位置值从 0 开始,所以在我们的示例中,我们将
raven
设置为 0,magpie
设置为 1,jay
设置为 2,corvid_num
为 3。最后的 3 显然是我们感兴趣的 3。
作者是否有权说 raven 的值应该为 0 而不是 magpie,如果这是一个错字,我的全部困惑都会消失。
在声明char const * const bird [ corvid_num ]
中, [ ]
之间的项是数组的大小。 在初始化器列表中, [ raven ] = " raven "
, [ ]
之间的项是所谓的指定初始化器,用于初始化数组中的特定项。
问题1:'[magpie] = "magpie"' 是否暗示'magpie'TH position 指的是值"magpie"。
是的。
问题 2:根据循环,bird [0] 如何等于“raven”,因为这是明确的而不是位置值。
因为枚举被命名为常量。 如果枚举常量( raven
等)没有明确给出一个数字,它会隐含地给出一个,从 0 开始。在你的例子中, raven
是枚举中的第二项,所以它的值是 1, raven
你在source 相当于输入1
。
正如您可能已经猜到的,位置值从 0 开始,所以在我们的示例中,我们将 raven 设置为 0,magpie 设置为 1,jay 设置为 2,corvid_num 设置为 3。最后的 3 显然是我们感兴趣的 3。
这是Gustedt - Modern C中的错误。 勘误表可能存在? 示例代码中的 output 是:
Corvid 0 is the magpie
Corvid 1 is the raven
Corvid 2 is the jay
值得注意的是,如果我们没有使用指定的初始化器,而是这样做了:
char const * const bird [ corvid_num ] =
{
"raven",
"magpie",
"jay",
};
那么 output 将改为
Corvid 0 is the raven
Corvid 1 is the magpie
Corvid 2 is the jay
每个enum
案例的值都是前一个案例的值加一,除非显式覆盖,第一个案例的值为零。 所以这里magpie
是0
, raven
是1
,等等(引用的部分说否则是错误的。)最后一个 case corvid_num
是数组中其他 case 的计数,因为那个 case 的+ 1
占了数组中的零 case开始。
数组初始化使用 C99 指定的初始化程序,它允许以任何顺序将值分配给特定索引,即[raven] = "raven"
初始化索引raven
(此处为1
)。 传统上可以按顺序列出每个值,但这样做可以重新排序枚举案例,而无需将更改与数组同步。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.