Most of C compiler store local variable in stack. you code behavior is like following.
-> first time call p()
1. **int y;** push y in top of stack. (here value y is 0 or garbage according to compiler because it take value of is memory location).
2. **printf ("%d ", y);** print value of y location.
3. **y = 2;** change value of y location with 2.
4. end of function scope of y finish ( i assume you know a variable scope in c) and pop from stack but not reset value of that location.
-> second time call p()
1. **int y;** push y in top of stack (memory location allocated of variable y is same as first call p() memory allocation of y so that here value y is 2 because in first call we set value 2 in this location)
2. **printf ("%d ", y);** print value of y location.
that`s why here 2 print in second call p().
for your reference see the following code, i print value and memory address of variable in this code.
void p ()
{
int y ;
printf ("value of y = %d \n", y);
printf ("address of y = %p \n", &y);
y = 2;
}
void q ()
{
int x ;
printf ("value of x = %d \n", x);
printf ("address of x = %p \n", &x);
x = 8;
}
void main ()
{
p();
q();
p();
}