Disclaimer: This question is strictly academic. The example I'm about to give is probably bad style.
Suppose in C I write a subroutine of this form:
char *foo(int x)
{
static char bar[9];
if(x == 0)
strcpy(bar, "zero");
else
strcpy(bar, "not zero"),
return bar;
}
Then, elsewhere, I use foo
as follows:
printf("%i is %s\n", 5, foo(5));
My mental model of pointers and static variables predicts that, in practice, the output of this printf will be
5 is not zero
...but is this actually required by the C standard, or am I in nasal demon territory?
To make things even worse, what about something like
strcpy(foo(5), "five");
My mental model says this should "work" unless it's explicitly illegal, though it's somewhat pointless since it doesn't affect the output of foo
. But again, is this actually defined by the standard?