C / C ++ enum and char * array

Designate the following code in the article and donโ€™t think that this is the standard C / C ++ syntax for the char * array. As a test, both Visual C ++ (visual studio 2005) and C ++ Builder Rad XE reject the second line.

Without using #define s, do everyone have any tricks / tips for storing enum and sorting the string array in sync without resorting to using STL?

More about curiosity.

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

as an aside, the article from which this came about is quite old, and I believe that it can work under GCC, but not verified.

+4
source share
4 answers

These are the designated C99 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

Unable to keep line and line synchronization. If I really needed it, I would write a script to grab enumeration declarations from source code and generate string arrays from this. I really hate doing this with macros.

UPDATE: here is a question from last year that discusses conversion of an enum string โ†’ (for printing in this case)

C ++: print enumeration value as text

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

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

Read about Assigned Initializers for Aggregate Types - C99 .

+4
source

This is the C99 syntax that is supported by GCC. With your requirements

  • no #define
  • no stl

you probably wonโ€™t find synchronization.

+1
source

I understand this is an old question, but it can help anyone looking for an easy way to keep multiple arrays / enums in sync.

In my case, I just wanted to check the compilation time to determine if my lists were out of sync, and since the sizeof operator is not evaluated before, the preprocessor does this, it was the easiest way to do this.

In a header file of some kind ...

 enum ColorType { Red=0, Blue, Green, ColorType_Max }; 

In the same header or in another file, maybe ...

 char const* ColorTypeNames[]= { "Red", "Blue", "Green" }; 

In the cpp file somewhere ...

 const int s_ColorTypeCount = (int)ColorType_Max; const int s_ColorNameCount = (int)(sizeof(ColorTypeNames)/sizeof(char const*)); const int s_ColorErrorA = 1/(s_ColorTypeCount/s_ColorNameCount); const int s_ColorErrorB = 1/(s_ColorNameCount/s_ColorTypeCount); 

Only if two sizes match will be equal to 1. s_ColorErrorA and s_ColorErrorB are equal to 1. Since the variables are constants, this will lead to a division of the compilation time by zero error when the two counter variables are different.

+1
source

Source: https://habr.com/ru/post/1338874/


All Articles