next up previous contents
Next: Modifying Global Variables Up: Scoping Rules Previous: Independent Scopes

   
Examing Global Variables from within Routines

Consider the procedure TheGood and the global variable outside defined below:

> outside := 1029384756:

> TheGood := proc( )
>  lprint('The value of variable outside is: ', outside);
> end:

> TheGood();
The value of variable outside is:  1029384756
Invoking the procedure TheGood prints out the value assigned to the global variable outside. This shows that the scope of outside includes the body of the procedure TheGood. We may examine the contents of any global variable as long as neither of the following two conditions are violated in your procedure3.2:
1.
The global variable does not appear in the left hand side of an assignment.
2.
The global variable does not appear as the variable in a for loop. Example: for glb from 1 to 10 do $\ldots$ where glb is a global variable.

If either of these conditions are violated, a local variable of the same name as the global variable is created and any values we assign to the local variable will not persist after the end of execution.

> outside := 1029384756;
>
> TheBad := proc( )                # an extension to the_good
>   outside := 2;                   # We think we're assigning to the
>   lprint('Outside: ', outside);   #  global copy of outside, but we aren't
> end:

> TheBad();
Outside:  2
> outside;
1029384756
Since outside appears on the left hand side of an assignment, a local variable also named outside is created. If we were extremely careful programmers, we would re-write TheBad as follows:
> TheBetter := proc( )
>   local outside;
>   outside := 2;
>   lprint('Outside: ', outside);  
> end:
Now, there is no confusion whatsoever about which outside you are referring to when performing the assignment.


next up previous contents
Next: Modifying Global Variables Up: Scoping Rules Previous: Independent Scopes
Gaston Gonnet
1998-09-15