I want to create a method get_name(...) which returns the name for an enum_value. The enum values are few, but can be up to 1^32 - 1 (so I don't think I can use an array mapping).
I did the following:
const char* get_name(type_t x) {
static const char* name_1 = "NAME_FOR_TYPE_1";
static const char* name_2 = "NAME_FOR_TYPE_2";
...
static const char* invalid = "INVALID";
switch (x) {
case type_1: return name_1;
case type_2: return name_2;
...
}
return invalid;
}
Then, I was told the following will also work:
const char* get_name(type_t x) {
switch (x) {
case type_1: return "NAME_FOR_TYPE_1";
case type_2: return "NAME_FOR_TYPE_2";
...
}
return "INVALID";
}
Is that true? Will it always work?
Am I not returning a pointer to temporary?