Global and Local variables
What’s the difference between global and local variables?
You probably know by now that. variables are used to store some data. You might also know that it’s called a variable because you can change the data value stored. So what is the difference between a global and local variable?
Global Variables
A global variable is available throughout the program. This means that you can access a global variable and even change its value from anywhere within the program. Since complex programs are separated into many different files it can get very tricky to figure out which line of code change the variable and that is why global variables are considered to be extremely poor programming!
Local Variables
Local variables are created within a subroutine (aka a function) and can only be used within that sub routine. The general rule is that you should only create a variable where it is needed. So use a local variable anywhere that it will suffice. Since a local variable only exists within the routine, they save memory. Also it’s easier to understand the program if, wherever possible, the variables are close to the code where they are used.
Because local variables only exist within the separating subroutine you can have the same variable name for different local variables as long as they are in separate subroutines.
Scope
Scope means were a variable can be accessed. So let global scope is everywhere and local scope is just within the sun routine. The best programmers limit the scope of a variable as much as possible.
An Example of Scope in a Function
In the DisplayMessage()
function here, day
is a local variable visible throughout the function. In other words its scope is the just within the function and not the whole program. Each hour variable is also local. However, each hour
variable only has scope (is only visible) within the if statement in which it was created. So there are three seperate variables called hour
. This will compile as each hour
variable is entirely seperate. However, hour
can not be accessed outside of its if statement.
GCSE Exam Questions
Exam questions will use the following style to represent variables.