Return pointer to temporary element C

Possible duplicate:
returns a pointer to a literal (or constant) character array (string)?

Is the code 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));

      

I'm worried that the function returns a pointer to a temporary object. What is the lifespan of such return values? Language - C89.

+3


source to share


2 answers


The code is fine. You are returning a pointer to a string literal that will be valid throughout your entire program.

From the C89 standard:



3.1.4 String literals

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

+6


source


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



+5


source







All Articles