# Variable scope

The scope of variables relates to how a variable is seen by a particular block of code. Let's look at an example.

    value as integer = 1

    do
    	myFunction ( )
    	sync ( )
    loop

    function myFunction ( )
    	print ( value )
    endfunction

At the start of this program the variable value is declared and assigned a value of 1. This is followed by a do loop, that calls our custom function myFunction and the sync command to update the screen. All that myFunction attempts to do is to print the contents of value on screen. This program will not work. Attempting to compile or run it will result in an error, telling you that the variable "value" is used without being defined or initialised within the function. The reason for this is that the variable is only visible to the area where it has been defined, in this case anything before or after the do loop can deal with it. The function declaration is considered another block of code, therefore it doesn't know about the existence of the variable value. Let's examine the program with a few changes.

    value as integer = 1

    do
    	print ( value )
    	myFunction ( )
    	sync ( )
    loop

    function myFunction ( )
    	value as integer = 2
    	print ( value )
    endfunction

This time myFunction declares a variable named value inside it, resulting in the code being valid, so it can compile and run, but we have already declared a variable called value outside of this function, so what is happening? Well, the way it works is that the variable declared inside of the function is within the scope of the function, so it's unique to the function. The program treats it as a different variable to the one declared outside of the function. When you run the program the values 1 and 2 will be displayed on screen because these are unrelated variables.