Hello guys and welcome back.
In this lecture we're going to discuss global variables.
So currently we've discussed local variables which are simply variables declared in a scope.
Now a global variable is a variable declared outside of a scope such as Here for example.
And what we've now done is we've created an ABC variable that can be accessed through multiple functions.
So ABC can be accessed here or it can be accessed here.
Now what if we create a variable named ABC here.
What happens.
Well it works.
Instead this ABC will be set on line 12.
When we say ABC could study it'll will change this one not this one.
Now in C variables can share the same name.
So long as they are not in the same scope.
So for example this is not allowed.
However
this is allowed and if we was to do ABC equals five here and then ABC equals 10 here.
What would happen is when we enter.
Well what would happen is here we create a variable named ABC.
We set it to 20.
We now create another variable called ABC that is unrelated to the one on line 11.
Here we set this one to 20.
We then set this one again to five online.
Online 15.
Here we now leave.
We now leave this scope.
So this variable gets removed deleted is no longer accessible.
And if you want to try and access it through its memory address it would be undefined behavior as explained
in previous videos.
When it comes to scopes when you leave a scope the variables can no longer be access safely.
Now online 18 you can see we set ABC to 10.
Now this changes this one on 11 not this one because this one is disappeared forever.
So not the one on line 14.
It changes this one.
Now if this wasn't here and we did ABC equals ten it would change the one in the global scope by here.
So I hope that explains global variables and how variables can share the same name on separate scopes.
So it always picks the one that's the closest to the top of itself.
So in short ABC it was 20 it would pick this one because this is the closest of the top of itself.
This wasn't here.
Then the one here in the global scope is the closest of the top of itself.
So that is how it works.