Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: how to declare a static function that returns a nonstatic string?

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;
}
like image 635
hbp Avatar asked Jan 30 '15 19:01

hbp


3 Answers

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.

like image 148
Jon Purdy Avatar answered Sep 24 '22 09:09

Jon Purdy


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:

  • The first returns a pointer to a static array, whose contents may be modified. Beware of concurrency and re-entrancy issues if you do that though.
  • The second allocates some heap-memory, initializes it with a string, and returns that. Remember to free it.
like image 21
Deduplicator Avatar answered Sep 25 '22 09:09

Deduplicator


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.

like image 28
Sourav Ghosh Avatar answered Sep 25 '22 09:09

Sourav Ghosh