开发者

C/C++ enum and char * array

开发者 https://www.devze.com 2023-02-09 20:28 出处:网络
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 bo开发者_如何学Ct

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 bo开发者_如何学Cth 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.


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


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.


This is C99 syntax, what is supported by GCC. With your requirements

  • no #define
  • no STL

you will probably not find a sync.


I realize this is an old question, but this might help anyone else looking for a simple way to keep multiple arrays/enums in sync.

In my case, I simply wanted a compile-time check to determine whether my lists were out of sync, and since the sizeof operator is not evaluated until after the preprocessor does it's thing, this was the simplest way to do that.

In a header file of some sort...

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

In the same header or some other file perhaps...

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

In a 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 when the two sizes match, will s_ColorErrorA and s_ColorErrorB equal 1. Since the variables are constants, this will generate a compile-time divide by zero error when the two count variables differ.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号