Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++ enum and char * array

Tags:

c++

c

enums

char

Ran accross the following code in an article and didn't think it was standard C/C++ syntax for the char* array. As a test, both Visual C++ (visual studio 2005) and C++ Builder Rad XE both reject the 2nd line.

Without using #defines, anyone have any tricks/tips for keeping enums and a string array sort of in sync without resorting to STL ?

More of a curiosity question.

enum TCOLOR { RED, GREEN, BLUE };

char *TNCOLOR[] = { [RED]="Red", [GREEN]="Green", [BLUE]="Blue" };

as an aside, the article this came from is quite old and I believe this might work under GCC but have not tested.

like image 334
Eric Avatar asked Dec 13 '22 16:12

Eric


2 Answers

These are C99 designated initializers. GCC supports them in C90 mode (and in C++) as an extension. Read about it here:

http://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html#Designated-Inits

There is no good way to keep enums und strings in sync. If I'd really need this, then I'd write a script to grab the enums declarations from the source code and generate the strings arrays from that. I really hate doing this with macros.

UPDATE: Here's a question from last year which discusses enum->string conversion (for printing in this case)

C++: Print out enum value as text

like image 106
Nordic Mainframe Avatar answered Dec 15 '22 05:12

Nordic Mainframe


char *TNCOLOR[] = { [RED]="Red", [GREEN]="Green", [BLUE]="Blue" };

This is allowed only in C99, not in C++03, C++0x, or any other version of C.

Read about Designated initializers for aggregate types - C99.

like image 41
Nawaz Avatar answered Dec 15 '22 06:12

Nawaz