简体   繁体   中英

Is it superfluous to use the static keyword inside functions for string literals?

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM