0

According to this string literals are always static. This makes me wonder whether the following functions do exactly the same:

static const char *foo1(void) {return "bar";}
static const char *foo2(void) {const char *bar = "bar";return bar;}
static const char *foo3(void) {static const char *bar = "bar";return bar;}

Is there any significant difference between foo1, foo2 and foo3 or not? In other words: Is using the static keyword superfluous when declaring string literals inside functions?

Andreas
  • 9,245
  • 9
  • 49
  • 97
  • The type of strings literals in ```C``` is an array of ```char```, but in ```C++```, it is an array of ```const char```. The ```static``` in the function declaration applies to linkage, in this case internal linkage. – Harith Dec 28 '22 at 11:27
  • ...which means that this function is only visible in this translation unit. In the declaration ```static const char *bar```, the static applies to the pointer ```bar```, not what it is being assigned with. – Harith Dec 28 '22 at 11:33

2 Answers2

3

They are completely equivalent. Here is GCC's output with -O2:

.LC0:
        .string "bar"
foo1:
        mov     eax, OFFSET FLAT:.LC0
        ret
foo2:
        mov     eax, OFFSET FLAT:.LC0
        ret
foo3:
        mov     eax, OFFSET FLAT:.LC0
        ret

And in any case, you are not applying static to the string literal itself. You are declaring the pointer bar to be a local static variable. But you don't use that pointer variable for anything but copying its value to the function return value. So it can't matter whether it is static or not.

user17732522
  • 53,019
  • 2
  • 56
  • 105
2

None of the static are related to the string literal.

static const char *foox(...

This static means something completely different. Functions will have only internal linkage.

static const char *bar = "bar";return bar;

This static does not have anything in common with the string literal. It affects only the variable bar which will have a static storage duration.

0___________
  • 60,014
  • 4
  • 34
  • 74