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.

有帮助吗?

解决方案

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.

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top