If a function is declared as
static char *function(...) { ... }
Does it mean that this is a nonstatic function that returns a static char *
, or a static function that returns a nonstatic char *
?
Compare the following two functions. Which one is the correct use?
static char *fn1(void)
{
static char s[] = "hello";
return s;
}
static char *fn2(void)
{
char *s = malloc(6);
strcpy(s, "world");
return s;
}
static
applies to the function, not its return type. Both of these functions are correct—the difference is that s
will be initialised once on the first call to fn1
, and all calls to fn1
will share s
; whereas in fn2
, a new s
will be allocated on every call. And since both fn1
and fn2
have static
linkage, they will be private to the translation unit (source file, approximately) where they are defined.
static
before the function applies to the function, not its type (or even part of it, like the return-type):
It means the function has static linkage, aka is translation-unit/file local (and thus very likely to be inlined).
Both functions are correct, though they have different semantics:
free
it.Both your function definitions are correct.
Point to note, static
here is used to limit the function to file scope, not to specify the return type, i.e., this function can be used [called] by the other functions present in the same file, but not by the functions which are present in some other files, though they might have been compiled and linked together to form the binary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With