Initializing Static Pointer Arrays

K&R demonstrates an example of initializing an array of pointers 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 the ideal internal static array application." But why is this so? Why not just make it an automatic pointer array?

+3


source to share


1 answer


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

With an array as a static variable, it is initialized once (before being called main()

, I believe, anyway, before the function is first used) and then stays the same. This is likely to be more efficient, and probably significantly more efficient (although it may not matter if you don't use the function month_name()

very heavily).



It would probably be better if there were some sorting commands const

lurking in the code; the calling function should not, of course, change 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];
}

      

+3


source







All Articles