枚举成员可以是 ANSI-C 中数组的大小吗?

标签 c gcc standards clang c89

我需要根据 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/

相关文章:

android - 如何理解bionic的bcopy.c中的这段代码?

C++ - 字符数组以某种方式初始化为错误的大小

c - DLL 中的函数未返回正确值

c++ - 指向成员转换的指​​针

c++ - 为什么编译器允许字符串文字不是 const?

java - 为什么不使用静态字符串数组?

c - Map<string, string> 在 C 中的实现

c - 为什么使用 OpenMP 会使代码运行速度变慢?

c - 如何知道文件描述符是否被打开?

linux - 在 Linux 操作系统中禁用 ASLR 后,虚拟到物理映射是否已修复