In this lecture I want to go over a very important concept called scope scope is the region of program
that you can access and use variables.
So far we've had our variables only in our main function like this x variable rate here.
So X it can only be used in this main function it can't use anywhere else in the program so I couldn't
have X being used in this other function that I called func x is x here.
And all so c the compiler is complaining to me.
So symbol X could not be resolved right.
So it doesn't understand what this symbol x is because X is local only to this main function can't use
X anywhere else.
Can.
So this is called a local scope.
So X has only local scope it's local to me.
Only so we saw another example of this in fact with the for loop.
So we had our FOR loop in we declare the inside for loop and we say I'm less than you know some number
say and then I plus plus and I said we couldn't do something like this.
Can't say I is this
is I Andel because I is local to only the for loop.
It's not you can't use I anywhere else sides inside this for.
And so it's local it's for live only just like x' local only to the main function.
Now we could have X be outside of the main function like this we could declare it in or define it up
here and then.
So let's just get rid of this.
Then we could have
the X being used in this function here.
And all a year is to distinguish it.
It run it and it says X equals 5.
That's this one right here.
So this line.
And then it says phunk X is 5.
So it actually did work.
So when you declare or define a variable outside of any function.
So here we have it above main and this phunk This is called global scope.
So it's global to the entire program.
And you may be asking why not just use global scope for all variables.
Well this is usually a bad idea.
In if a function modifies a global variable x here and you're not aware or you forgot maybe you wrote
it a little while ago and you can't remember.
You might get some very strange results.
You don't usually want variables being modified without us understanding why it's being modified and
all variables really make things harder and it's hard to reason about.
So we're never going to be using global variables in any of our programs and I suggest you don't use
it either in the C really understand how things really work.
So these will be seeing some other examples of scope in some upcoming lectures.