سؤال

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