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?
CodePudding user response:
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.
CodePudding user response:
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.