3

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?

Elad Weiss
  • 3,662
  • 3
  • 22
  • 50
  • What is "temporary"? did you read about scopes and lifetimes? Which part was confusing? See, sharing your research will help others, too. – Sourav Ghosh Apr 19 '17 at 07:30

1 Answers1

13

String literals are stored as arrays that have a lifetime of the full program. Pointers to them never become invalid.

So it's safe to do the second alternative, and there are not "temporaries" involved.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621