枚举成员可以是ANSI-C中数组的大小吗? [英] Can enum member be the size of an array in ANSI-C?

查看:495
本文介绍了枚举成员可以是ANSI-C中数组的大小吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要根据枚举有多少个元素来分配一个数组。我做了以下:

I need to allocate an array according to how many elements the enum have. I did the following:

enum { A, B, C, LAST };
char buf[LAST];

这很好,即使 -ansi -pedantic 标志。但我不知道它是一个GCC或clang(支持大多数,如果不是所有的GCC扩展)扩展或真正允许的ANSI C标准,并将在任何C编译器与ANSI-C std工作良好。

That works fine,even with -ansi -pedantic flags. But I'm not sure if it's a GCC or clang(wich supports most,if not all GCC-extensions) extensions or really allowed by the ANSI C standard and will works fine in any C compiler with ANSI-C std. Can someone clarify it?

推荐答案

C89(第3.5.2.2节)和C99(第6.7.2.2节)标准都定义了枚举同样的方式:

Both the C89 (section 3.5.2.2) and C99 (section 6.7.2.2) standards define enums the same way:


6.7.2.2枚举规范(第3段),http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf

3.5.2.2枚举说明符(第3段), http://flash-gordon.me.uk/ansi.c.txt

两者读取:


[...]枚举常数表达式的枚举常数。如果第一个枚举器没有=,它的枚举常数的值为0.每个后续枚举器没有定义它的枚举常数作为通过将1加到前一个枚举常量的值获得的常量表达式的值。 [...]

[...] 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. [...]

因此,在您的语法中,任何符合标准的编译器都会正确运行您的代码。

Therefore, in your syntax, any standard-compliant compiler will run your code correctly.

这篇关于枚举成员可以是ANSI-C中数组的大小吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆