3

Possible Duplicate:
returning a pointer to a literal (or constant) character array (string)?

Is the code below correct?

const char* state2Str(enum State state)
{
   switch (state)
   {
      case stateStopped: return "START";
      case stateRunning: return "RUNNING";
      default: return "UNKNOWN";
   }
}

printf("State is: %s\n", state2Str(stateRunning));

What worries me is that the function return a pointer to a temporary object. What is the lifetime of such return values? Language is C89.

Community
  • 1
  • 1
Vitaly P
  • 1,121
  • 3
  • 11
  • 21

2 Answers2

6

The code is fine. You're returning a pointer to a string literal which will be valid for the duration of your program.

From the C89 standard:

3.1.4 String literals

A character string literal has static storage duration and type ``array of char ,'' and is initialized with the given characters.

simonc
  • 41,632
  • 12
  • 85
  • 103
5

In the case of the code in your question, you are not returning pointers to temporaries. You are returning a pointer to a string literal which is stored either among the code or among the global data. The duration of all string literals is the lifetime of the program.

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