Main Content

Variable Scope

Archive - Originally posted on "The Horse's Mouth" - 2004-10-22 07:32:43 - Graham Ellis

One of the vital topics on all our programming courses is that of variable scope. Variable Scope may be defined as the area of a program in which a variable is visible, and how long that variable is accessible for.

Why do I describe variable scope as a vital subject when you can write simple programs in almost any of the languages we teach without any appreciation of the issue? Because it becomes vital as your code grows into a series of blocks - sometimes named (functions in PHP, procs in Tcl, def in Python, subs in Perl, methods in Java) and sometimes not (for example { to } blocks in Perl, inset blocks in Python). As a new programmer, you might think that all variables should be visible everywhere (this is often know as "default global"), but that's a bad default - the only language that has this default is Perl and that's for historic reasons. It will change at Perl 6!

Why is "default global" a bad default? Because it means that when you combine code from two blocks / files / sources, each must have variables who's names don't conflict with and other name in any other module and in practice that's almost impossible to ensure. Looking at a real-life example, in our household "Charlie" refers to the cat, but in the Royal Family "Charlie" might be used to refer to the Prince of Wales. Let's say that the Royal family comes to visit us (yeah, improbable I know!), and someone says "come here Charlie" .... are they going to get a cat or a prince?