James Kuyper
4/2/2011 4:14:00 PM
On 04/02/2011 11:20 AM, pozz wrote:
> #include <stdio.h>
> #include <stdint.h>
> #include <stdlib.h>
>
> char * foo(void) {
> static char str[32];
> sprintf (str, "foo");
> return str;
> }
>
> int main(void) {
> printf("%s", foo());
> return 0;
> }
>
>
> Is it always possible to use a static variable (declared inside a
> function) outside its declaration block, as in the example above?
Sure. Why not? The key issue is whether or not the object pointed at by
the pointer still exists; since it is declared 'static', the answer is
"yes".
> Do you consider this a bad practice?
Not in itself.
However, static variables do tend to interfere with re-entrancy. For an
example of why this could be problematic, look at strtok(), and consider
what would happen if you wanted to parse two different strings in
parallel using strtok(). Or, equivalently, think about a case I actually
ran into: a calling function calls strtok() in a loop to parse one
string; in that same loop, it calls another function which also uses
strtok() to parse an entirely different string. Both functions were
written by different people, at very different times. One was part of a
library, the other was part of a program that used that library. I was
called in to investigate the bizarre consequences of linking the program
to that library.
My advice: use static variables only if you're certain that you will
never want to re-use the code in any context where you might want to
have two separate copies of the information stored in those variables.
--
James Kuyper