Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can enum member be the size of an array in 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];

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?

like image 990
Jack Avatar asked Dec 07 '12 20:12

Jack


1 Answers

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 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

Both read:

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

like image 110
utopianheaven Avatar answered Oct 16 '22 10:10

utopianheaven