Reputation: 53
Why compiler shows the value of x
as 0
if I define int x;
inside of for
loop. But when removing int x
from for
loop gives the value of x
as 10
.
#include<stdio.h>
int main() {
int x = 0, i;
for(i = 1; i <= 10; i++) {
int x;
x = 10;
}
printf("%d", x);
}
Upvotes: 1
Views: 98
Reputation: 73
As explained before, if you define a variable inside the for
loop int x; x = 10;
it will create a new variable that is only accessed inside the for
loop.
So when you create variable x
in main
then create variable x
in the for
loop, you are currently referring the print printf("%d", x);
to the first x
declared in main
and that is why it is printing 0. This is because you initiated it to 0
in the line int x = 0, i;
and it never changed. You never actually printed the x
you initiated in the for
loop.
But when you remove the int x;
form the for
loop, there is only one x
initiated and you changed the value of x
to 10
inside the loop. When you print x
it gives you 10
which is the value that was assigned to it inside the for
loop.
Hope this is not confusing.
Upvotes: 1
Reputation: 151
Because the scope of int x
inside the for loop is limited to that for loop only.
for(i=1;i<=10;i++) { int x; x=10; /limited to this loop only, can't use outside of for loop/ }
And int x outside of for loop but inside main() function would be available to all function inside main()
If you want to get value of i
you may try this:
x=i;
instead of
int x;
x=10;
Upvotes: 2
Reputation: 1877
If you have int x
inside your for-loop, you create a new x
variable. That means that you effectively have two x
variables in your program, one which can be accessed from your main()
-function and one which only can be accessed inside the for-loop. If you access x
from within the for-loop, the compiler will choose the closest one.
If you were not to have int x
inside your for-loop, there would only be one x
and your program would output 10
.
Upvotes: 2