18.5. More on local and global variables

[<<<] [>>>]

Although ScriptBasic following the good old BASIC conventions implicitly defining all variables not declared as local to be global inside subroutines and function this is not always a good approach. This is quite convenient in case of small programs, but may harm when writing large programs. One programmer may sloppily write a function that uses the variable I as a loop variable in a FOR loop. This is quite common. Not declaring this variable to be local is also common. Debugging days finding out why the global variable I is changing in a code fragment calling a function which is calling a function which is calling the function containing the loop is also quite common.

As you could see there is a declare option command that requires the programmer to declare all variables, but it does not solve this problem.

The solution in more modern languages is that all variables inside functions and subroutines are local unless they are explicitly declared to be global. ScriptBasic can also follow this way. To do this you have to insert the command:

declare option DefaultLocal

This will mean that all variables inside a function or subroutine following this line will be local unless explicitly declared to be global. This can be used to prevent programming bugs like the one described above. This will make the


[<<<] [>>>]