Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
Read this program carefully. The procedure declares its own Score.
DECLARE Score : INTEGER
PROCEDURE AddPoints(Points : INTEGER)
DECLARE Score : INTEGER
Score ← Points * 2
OUTPUT Score
ENDPROCEDURE
Score ← 10
CALL AddPoints(7)
OUTPUT ScoreWhat are the two outputs? Explain the result with the words local and global.
A procedure does a job: PROCEDURE Name(Param : TYPE) ... ENDPROCEDURE, run with CALL Name(value). A function returns one value: FUNCTION Name(Param : TYPE) RETURNS TYPE ... RETURN value ... ENDFUNCTION, used inside an expression without CALL. A variable declared inside a subroutine is local; one declared in the main program is global.
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, go through the solution one step at a time, and check each step against your own.
Step 1. Inside the procedure. The procedure declares Score, so inside it that name means a local variable. It is set to and output: the first output is 14.
Step 2. Back in the main program. The local Score is gone. The name now means the global Score, which is still 10. The second output is 10.
Answer: 14, then 10.
Watch out. Giving a local variable the same name as a global one is legal, but it is easy to misread. In your own programs choose different names.
Log in to join the discussion.
Loading…