我需要根据 enum
有多少元素来分配一个数组。我做了以下事情:
enum { A, B, C, LAST };
char buf[LAST];
即使使用 -ansi -pedantic
标志也能正常工作。但我不确定它是 GCC 还是 clang(支持大多数,如果不是所有 GCC 扩展)扩展,或者真的被 ANSI C 标准允许,并且在任何带有 ANSI-C std 的 C 编译器中都能正常工作。有人可以澄清一下吗?
最佳答案
C89(第 3.5.2.2 节)和 C99(第 6.7.2.2 节)标准都以相同的方式定义枚举:
6.7.2.2 Enumeration specifiers (Paragraph 3), http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf
3.5.2.2 Enumeration specifiers (Paragraph 3), http://flash-gordon.me.uk/ansi.c.txt
双读:
[...] 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. [...]
因此,在您的语法中,任何符合标准的编译器都会正确运行您的代码。
关于枚举成员可以是 ANSI-C 中数组的大小吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13770314/