#include <stdio.h>
int a;
void myproc()
{
int a = 2;
while (a == 2)
{
int a = 3;
printf("a = %d\t", a);
break;
}
printf("a = %d\t", a);
}
int main()
{
a = 1;
myproc();
printf("a = %d\t", a);
return (0);
}
I expected the above code to print: a = 3 a = 3 a = 1 However, it prints: a = 3 a = 2 a = 1 Can someone please provide a valid explanation?
Here is an explanation -- see the commentary below.
#include <stdio.h>
int a;
void myproc()
{
int a = 2; // (1) a = 2
while (a == 2) // true
{
int a = 3; // (2) new scope, new a = 3
printf("a = %d\t", a); // (X) prints 3 as it gets the 'nearest a' in the scope
break;
} // throws away a=3 from (2)
printf("a = %d\t", a); // (Y) Uses (1) i.e. 2 and print it
}
int main()
{
a = 1;
myproc();
printf("a = %d\t", a); // (Z) Just prints 1 as the scope is not effected by myproc
return (0);
}
So this will print (X) (Y) and (Z)
i.e. 3 2 1
Yes, they are local automatic variables and are pushed on and popped off the stack when you enter and exit a given scope unless the compiler decides to make certain optimizations (such as storing them in registers, etc.) But for a given variable, the most locally scoped version of that variable is used when accessing it. For instance, in C89 should you decide to declare your loop counters within a for-loop declaration, the following typically produces a compiler error:
for (int i=0; i < N; i++)
for (int i=0; i < J; i++)
printf("%d", i);
The value of i
printed will always be the value of i
declared in the inner for-loop, since that is the most locally scoped version of i
.
"Within a loop"?
The question you are asking has absolutely no relation to any loops at all. There's no difference between what you have in your code and the ordinary
int a;
void myproc()
{
int a = 2;
{
int a = 3;
printf("a = %d\t", a);
}
printf("a = %d\t", a);
}
Each nested block has it own variables. That's all there is to it. And it has nothing to do with any loops.
The declaration that is really related to the loop would be the declaration made in the header of the loop, as in
int a = 3;
for (int a = 0; a < 10; ++a)
{
...
}
printf("a = %d\n", a); // <- prints `3`
That a
declared in the for
header is still local to the loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With