c - 声明与全局、局部和静态同名的变量

标签 c variables declaration

我有以下代码片段,我必须分析输出结果:

#include <stdio.h>

  void f(int d);

  int a = 1, b = 2, c = 3, d = 4;

  int main(){
    int a = 5, c = 6;
    f(a);
    f(b);
    f(c);
    printf("%d %d %d %d\n",a,b,c,d);
    return 0;
  }

  void f(int d){
    static int a = 0;
    a = a + 7;
    b = a + d;
    c++;
    d--;
    printf("%d %d %d %d\n",a,b,c,d);
  }

我得到的输出如下:

7 12 4 4  
15 26 5 11  
21 27 6 5  
5 27 6 4  

这让我很困惑。我注意到在所有 3 个函数调用中全局声明 a遭受分配并且在printf()来自 main() body amain() 中声明被打印出来。但是,我不确定其余变量的行为。这是未定义的行为还是实际上有意义?

最佳答案

int a = 1, b = 2, c = 3, d = 4; ---> 全局变量

int main(){
    int a = 5, c = 6;         ---> Shadows the global `a` and `c`

....

void f(int d){
    static int a = 0;         ---> local static variable visible only inside `f`

...

关于c - 声明与全局、局部和静态同名的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21183675/

相关文章:

c - #行和字符串文字连接

在自己的处理程序中捕获信号

c - 在 Switch 语句中使用字母

ios - 在切换案例中声明UI对象

c - 当缓冲区太大时 fgets() 会阻塞

php - 如何使用 JSEDITABLE 获取 $_REQUEST ['id' ] 等字段

php - 带有 $variable 的 LIKE 运算符

javascript - 在 redux 函数中重构变量

php - 空变量在php中定义

c++ - 在 Xcode 下的 C++ 中声明 int 数组