3

K&R demonstrates an example of initializing a pointer array as follows:

char *month_name(int n)
{
    static char *name[] = {
    "Illegal month",
    "January", "February", "March",
    "April", "May", "June",
    "July", "August", "September", 
    "October", "November", "December"
    };

    return (n < 1 || n > 12) ? name[0] : name[n];
}

K&R states that "this is an ideal application for an internal static array". But why is this so? Why not just make this an automatic pointer array?

3
  • 4
    An automatic array needs initialisation every time it is called. I would suggest: compile both versions of the code and look at the generated assembly. Commented Aug 30, 2014 at 15:57
  • 1
    I'm not experienced enough to parse that comment. What would that tell me? Commented Aug 30, 2014 at 16:01
  • Most debuggers will allow you to look at the assembly code that the compiler generated. By looking at the assembly code, you can learn a lot about how the compiler works, and you will definitely learn things that will make you a better C programmer. Of course, the prerequisite is that you learn how to read the assembly language of the processor that you are using. Commented Aug 30, 2014 at 16:52

1 Answer 1

3

If the array was an automatic variable, each function call would have to initialize thirteen pointers, and then return one of them to the calling code.

With the array as a static variable, it is initialized once (before the main() is called, I believe; at any rate, before the function is first used), and thereafter remains unchanged. This is likely to be more efficient, and probably measurably more efficient (though it might not matter unless you're using the month_name() function very intensively).

It would probably be better if there were some const qualifiers lurking in the code; the caller of the function should certainly not modify the result string:

const char *month_name(int n)
{
    static const char * const name[] =
    {
        "Illegal month",
        "January", "February", "March",
        "April", "May", "June",
        "July", "August", "September",
        "October", "November", "December"
    };

    return (n < 1 || n > 12) ? name[0] : name[n];
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.