Search code examples
cfunction-prototypes

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;
}

Solution

  • 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.