0

I declared local variable b in function count , and local variable b in function count2, I thought they are different variables, but variable b in count2 still hold the same value , what is happening here ? Can someone explain it to me please?

#include<stdio.h>

int a;

int count2() {
    int b ;
    printf ("\n value of b2 variable for second time  is : %d ",b);   
  }

int count() {
    int b = 2;
    b++;
       
    printf ("\n value of b variable is : %d ",b);
    b = 99;
  }

int main() {
    printf ("value of a variable is : %d ",a);
    count();
    count2();
}
user10191234
  • 531
  • 1
  • 4
  • 24
tuan anh
  • 1
  • 1
  • 3
    You have not initialised the variable with a value so the results is undefined behaviour. Give it a value and then try. – Andrew Truckle Sep 14 '20 at 07:07
  • 2
    Think hard - what is the value of `b` in `int b ;`? When you access it, what type of behavior is invoked? (hint: *Undefined*) – David C. Rankin Sep 14 '20 at 07:13
  • 1
    C uses stack for variable space. When you declare b, a space is allocated from the stack. You store your first value there. After its scope, the space is freed but the memory isn't wiped. When you declare a variable again, the compiler allocates the same space of previous b as it is free now. But the value of the old b is still there, and you aren't initializing the second b, so you get the same old number. You don't nee to use the same variable name either. In count2(), the old value of b is acting as garbage value. –  Sep 14 '20 at 07:19
  • Change `count` to define these variables `int a=1, b=2, c=3;` and try again.. – Gerhardh Sep 14 '20 at 07:44
  • 1
    @Gerhardh `a` is initialized to zero – klutt Sep 14 '20 at 07:46
  • @klutt That's not the point. In `count` there is no `a` yet. My change is only meant to change stack layout (unless the compiler optimizes them out) and make it more visible that variables `b` in both functions are indeed not related. – Gerhardh Sep 14 '20 at 07:49
  • Out of curiousity: What value did you get in `count2`? Was it `3` or `99`? – Gerhardh Sep 14 '20 at 07:51

0 Answers0