Global vs local variables in nested procedures

This is where most of us started. Classic Spectrum basic.

Moderator: Programming Moderators

User avatar
Protocultor
Posts: 21
Joined: Tue May 30, 2017 12:54 am

Global vs local variables in nested procedures

Postby Protocultor » Fri Aug 14, 2020 6:32 pm

Today I learned: variables' context in a procedure is inherited from where the procedure was called.
Consider the following program:

Code: Select all

#program global
#autoline 10,10
; Global vs Local
;
LET %a=10
PROC printA()
PROC someProcedure()
PROC printA()
STOP
;
DEFPROC someProcedure()
LOCAL %a
LET %a=40
PROC printA()
ENDPROC
;
DEFPROC printA()
PRINT %a
ENDPROC
Its result is:

Code: Select all

10
40
10
...since the call of printA inside someProcedure takes the local var from that procedure, and not its global value.

Who is online

Users browsing this forum: No registered users and 2 guests