Returning a temporary const char * - will it work

I want to create a get_name (...) method that returns the name for enum_value. The enum values ​​are few and far between, but can be up to 1 ^ 32 - 1 (so I don't think I can use 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;
}

      

I was then told that the following would 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";
}

      

It's true? Will it always work?

Am I not returning a pointer to a temporary?

+3


source to share


1 answer


String literals are stored as arrays, which have the lifespan of the complete program. Pointers to them never become invalid.



So it's safe to do the second alternative, and there are no "temporary" ones involved.

+13


source







All Articles