加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如果sizeof空枚举在C中是4?

发布时间:2020-12-16 10:44:28 所属栏目:百科 来源:网络整理
导读:考虑以下程序(参见实时演示 here) #include iostreamint main(){ enum days{}d; std::coutsizeof(d);} 当使用g 4.8.1进行编译时,它会在本地计算机上打印4作为输出.它如何在这里占用4个字节?在给定链接中的gcc 6.0上,我也使用了`-pedantic-option,但它编译得
考虑以下程序(参见实时演示 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语言,语法只需要一个枚举器.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读