Search code examples
cpointersreturntemporary

Return pointer to a temporary in C


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.


Solution

  • 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.