gpt4 book ai didi

c++ - C++ 中空枚举的大小如何为 4?

转载 作者:太空狗 更新时间:2023-10-29 19:37:23 24 4
gpt4 key购买 nike

考虑以下程序(参见现场演示 here)

#include <iostream>
int main()
{
enum days{}d;
std::cout<<sizeof(d);
}

当使用 g++ 4.8.1 编译时,它在我的本地机器上打印 4 作为输出。这里怎么占4个字节?在给定链接中的 gcc 6.0 上,我也使用了 `-pedantic-option,但它仍然可以正常编译。

那为什么在 C 中不允许呢?我在 gcc 4.8.1 中尝试了以下程序。 (查看现场演示 here)

#include <stdio.h>
int main(void)
{
enum days{}d;
printf("sizeof enum is %u",sizeof(d));
}

编译器给出以下错误:

4   12  [Error] expected identifier before '}' token

5 36 [Error] 'd' undeclared (first use in this function)

5 36 [Note] each undeclared identifier is reported only once for each function it appears in

是否允许在 C++ 中使用空枚举,但在 C 中不允许?

最佳答案

C++ 不是 C。对于 C++,来自 [dcl.enum]:

For an enumeration whose underlying type is not fixed, the underlying type is an integral type that can represent all the enumerator values defined in the enumeration. [...] It is implementation-defined which integral type is used as the underlying type except that the underlying type shall not be larger than int unless the value of an enumerator cannot fit in an int or unsigned int. If the enumerator-list is empty, the underlying type is as if the enumeration had a single enumerator with value 0.

所以枚举器的基础类型(决定它的大小)就好像它里面只有一个 0,尽管实际类型是实现定义的。它可以是 1(int8_t 当然可以容纳 0),但绝对不会大于 4。在这种情况下,您得到 4,这是完全合理的。

对于 C,语法只需要一个枚举器。

关于c++ - C++ 中空枚举的大小如何为 4?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33307461/

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