Home > front end >  How can local variable be changed by statement variable?
How can local variable be changed by statement variable?

Time:12-11

I am a complete beginner, learning from youtube videos. And i am confused in this little concept here. The value of sum is '0' outside the scope of for loop. then we change it inside the scope of for loop. how come it is not still '0' when we print it outside the for loop. I know it's a stupid question. but from what i read , it should not change outside the scope of for loop ? I just want to learn.

#include<iostream>
using namespace std;
int main(){
    int n =10 , sum=0;
    for (int i = 0; i <= n; i  )
    {
       sum  = i;
    }
    cout<<sum<<endl;
    return 0;

}

CodePudding user response:

This is just how lexical scopes work.

sum is defined in a scope enclosing the body of the for loop so it is in scope in the body of the for loop. It's the other direction this doesn't work in i.e. if there was some local variable foo declared in the body of the for loop you could not access the value of foo in the enclosing scope after the for loop terminates.

  • Related