Will a value live perpetually when there's no reference to it?

前端 未结 8 1244
鱼传尺愫
鱼传尺愫 2021-02-13 07:02

Suppose the following minimal code:

#include 
char character = \'c\';
int main (void)
{
    char character = \'b\';
    printf(\"The current value         


        
8条回答
  •  时光说笑
    2021-02-13 07:51

    It will live on (till the program dies, as any static-storage variable would) and you can still get to it:

    #include 
    char character = 'c';
    int main (void)
    {
        char character = 'b';
        printf("The current value of head is '%c'\n", character);
        {
            extern char character;
            //in this scope, overrides the local `character` with 
            //the global (extern?) one
            printf("The current value of head is '%c'\n", character);
        }
        printf("The current value of head is '%c'\n", character);
    }
    /*prints:
    The current value of head is 'b'
    The current value of head is 'c'
    The current value of head is 'b'
    */
    

    The local extern declaration doesn't work reliably/portably for static globals, though you can still get to them through pointers or through a separate function.


    ( Why isn't static char character='c'; int main(){ char character='b'; { extern char character; } } reliable with the global being static?

    6.2.2p4 seems like it wants to make it work for statics too, but the wording is ambiguous (a prior declaration has no linkage and another has static/extern linkage so what now?).

    6.2.2p4:

    For an identifier declared with the storage-class specifier extern in a scope in which a prior declaration of that identifier is visible,31) if the prior declaration specifies internal or external linkage, the linkage of the identifier at the later declaration is the same as the linkage specified at the prior declaration. If no prior declaration is visible, or if the prior declaration specifies no linkage, then the identifier has external linkage.

    My clang 6.0.0 is accepting it with a static char character='b'; but my gcc 7.3.0 isn't.

    Thanks to Eric Postpischil for pointing out the ambiguous possibility of this being usable with static too. )

提交回复
热议问题