문제

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