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

前端 未结 8 1218
鱼传尺愫
鱼传尺愫 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:36

    You have two separate variables named character: one at file scope set to 'c', whose lifetime is the lifetime of the program, and one in main set to 'b', whose lifetime is that of its scope.

    The definition of character in main masks the definition at file scope, so only the latter is accessible.

    0 讨论(0)
  • 2021-02-13 07:37

    Normaly, the global variable will stay. Since your local variable only shadows the name, it doesn't affect the storage.

    But it could also depend on linker settings. Linker could optimize the unsused global variable out.

    0 讨论(0)
  • 2021-02-13 07:45
    #include <stdio.h>
    char character = 'c';
    int main (void)
    {
        char character = 'b';
        printf("The current value of head is %c\n", character);
        printc();
    }
    
    void printc()
    {
        printf("%c", character);
    }
    

    It makes it all clear. It is not destroyed it is just shadowed.

    Output: The current value of head is b
    c

    0 讨论(0)
  • 2021-02-13 07:48

    After the declaration of character in main, any reference to character in that function refers to that one, not the one at global scope. We call this shadowing.

    As for the effect on memory, you can't say due to the as-if rule adopted by the language: a compiler might optimise to

    #include <stdio.h>
    int main()
    {
         printf("The current value of head is b");
    }
    

    for example.

    0 讨论(0)
  • 2021-02-13 07:49

    Although global variables exist from the start to the end of the execution of a program, they are not automatically accessible.

    A global variable is accessible starting from the location in the file where the global variable is defined or declared until the end of the file.

    If in a function scope one defines a variable with the same name, the global variable will exist, but will not be accessible.

    0 讨论(0)
  • 2021-02-13 07:49

    "shadowing" the global character variable hides the variable from the main function, but it will still be a part of the program.

    If character variable was declared as static, then the compiler might warn that character variable is never used and character will be optimized away.

    However, character variable is not declared as static; the compiler will assume that character variable might be accessed externally and keep character variable in the memory.

    EDIT:

    As noted by @Deduplicator, linker optimizations and settings could omit the variable from the final executable, if permitted. However, this is an edge case that won't happen "automatically".

    0 讨论(0)
提交回复
热议问题