declaration of variables with same name as global,local and static

前端 未结 5 1498
北海茫月
北海茫月 2020-12-30 17:07

I have the following code snippet and I have to analyse what the output will be:

#include 

  void f(int d);

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


        
5条回答
  •  独厮守ぢ
    2020-12-30 17:50

     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);
       }
    

    That's right you declared global int a and global void function f but also you have declared static variable a Whenever function has called, function is refering a variable of function. if you want to avoid this problem, you should make a pointer of global variable, and refering a pointed address's value global variable. As you know static variable is keep their last value until end of program.

    each function's variable is exactly going to placed in "Stack" unless allocated by malloc. And global variable is "Heap". I am not sure but if you disassembly your program, static value a would go to stack and treated with PUSH and POP instruction.

提交回复
热议问题