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?
What you’ve written is OK; there are no nasal demons awaiting you. Even the
strcpy()example is ‘OK’ because you are not trampling beyond the bounds of the array. That ‘OK’ is in quotes because it is not a good idea, but as written, there is no out of bounds memory access and so no undefined behaviour. Thestaticdata in the function is there throughout the program’s lifetime, containing the last value that was written to it.There could be problems if you try:
You will get the wrong answer for one of the two numbers, but it is not defined which will be the wrong answer.