Reputation: 25
I'v got question when I practiced section 5.8(page 113) of K & R The C Programming Language.
original source code is here
/* month_name: return name of n-th month */
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];
}
And I already know that we can't return local variable's pointer because it's from stack and it will be destroyed(?) after function return. But in this example they use static to remain that variable.
The question is "Why they still work after I delete static notation".
I changed code to
/* month_name: return name of n-th month */
char *month_name(int n)
{
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];
}
and they still work very well.
BUT. if I return name
instead of name[n]
, it doesn't work as I expected.
Why does it work?
Upvotes: 0
Views: 73
Reputation: 170240
It still works because the array contains pointers to string literals. String literals have static storage duration even if the array the holds their addresses doesn't.
In fact an optimizing compiler should wise up to the fact, and produce identical code in both cases.
When you return name
however, the same rules that you noted apply. So you get undefined behavior. Although unless you change the return type of the function, then returning name
shouldn't compile, since char*
and char**
are incompatible types.
Upvotes: 3