选择静态全局.为什么?

-3 c static global-variables

以下代码的输出为0.

int account=2;

int main()
{
    static int account;
    printf("%d",account);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

为什么它选择静态变量而不是全局变量?因为我所理解的是全局变量和静态变量都存储在堆中而不是存储在函数堆栈中,对吧?那么它用什么方法来选择一个而不是另一个?

dbu*_*ush 25

如果在多个范围内存在多个具有相同名称的变量,则最内部范围中的变量是可访问的变量.隐藏了更高范围的变量.

在这种情况下,您已account定义main.这会隐藏account在文件范围内声明的变量.main声明内部变量内部的事实static不会改变它.

虽然static对局部变量的声明意味着它通常存储在与全局变量相同的位置,但是当名称相同时,它与视图无关.


Jab*_*cky 7

考虑这个小的自我解释程序:

#include <stdio.h>

int bar = 123;     // global variable, can be accessed from other source files

static int blark;  // global variable, but can be accessed only in the same
                   // source file

void foo()
{
  static int bar;  // static variable : will retain it's value from
                   // one call of foo to the next
                   // most compilers will warn here:
                   // warning  declaration of 'bar' hides global declaration

  printf("foo() : bar = %d\n", bar);  // won't use the global bar but the
                                      // local static bar
  bar++;
}

void quork()
{
  int bar = 777;   // local variable exists only during the execution of quork
                   // most compilers will warn here as well:
                   // warning  declaration of 'bar' hides global declaration

  printf("quork() : bar = %d\n", bar);  // won't use the global bar but the
                                        // local bar
  bar++;
}

int main() {
  foo();
  foo();
  printf("main() 1 : bar = %d\n", bar);
  bar++;
  quork();
  quork();
  foo();
  printf("main() 2 : bar = %d\n", bar);
  printf("blark = %d\n", blark);
}
Run Code Online (Sandbox Code Playgroud)

输出:

foo() : bar = 0
foo() : bar = 1
main() 1 : bar = 123
quork() : bar = 777
quork() : bar = 777
foo() : bar = 2
main() 2 : bar = 124
blark = 0
Run Code Online (Sandbox Code Playgroud)