过程与 BYREF
此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
English
CALL runs a procedure
- A procedure is a named block. It does a job and returns no value.
- Define it with
PROCEDURE…ENDPROCEDURE, and run it withCALL. - Parentheses are written even when there are no parameters.
English
PROCEDURE ShowRule()
OUTPUT "----------"
ENDPROCEDURE
CALL ShowRule()
OUTPUT "Club results"
CALL ShowRule()
- One definition, two
CALLs: the line is printed twice. The definition alone prints nothing.
English
By value is the default
- If no mode has been specified, parameters start by value: the procedure gets a copy.
- Changing the copy does not change the caller's variable.
BYVALexplicitly selects a copy. At the start of a parameter list it is the default; afterBYREF, writeBYVALto switch back.
English
PROCEDURE Show(Number : INTEGER)
Number ← Number + 1
OUTPUT Number
ENDPROCEDURE
DECLARE FirstNumber : INTEGER
FirstNumber ← 5
CALL Show(FirstNumber)
OUTPUT FirstNumber
English
BYREF passes the real variable
BYREFmeans the parameter is the caller's variable. A change is still there afterCALL.- A mode keyword continues across later parameters until another mode keyword changes it.
BYREF FirstValue : INTEGER, SecondValue : INTEGERmakes both parameters references. - Do not pass a parameter to a function by reference. Use
BYREFon a procedure.
English
PROCEDURE AddVisit(BYREF Visits : INTEGER)
Visits ← Visits + 1
ENDPROCEDURE
DECLARE Count : INTEGER
Count ← 0
CALL AddVisit(Count)
CALL AddVisit(Count)
CALL AddVisit(Count)
OUTPUT "Visits: ", Count
| After | Count with BYREF |
Count if it were by value |
|---|---|---|
first CALL |
1 | 0 |
second CALL |
2 | 0 |
third CALL |
3 | 0 |
- A procedure that must change two of the caller's variables needs
BYREFon both parameters.
English
Common mistakes
CALLbefore a procedure. NeverCALLa function.- IGCSE 0478 has no
BYREF. On that paper every parameter is a copy.
English
Now you try
- Write a procedure with no parameters, then one that swaps two integers. A swap changes both variables, so think about which mode each parameter needs.
English
Independent transfer
The final task has no supplied algorithm. Plan its inputs, processing and outputs, then solve it before opening support. Check more than the sample case.
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
写一个没有参数的过程 Greet,它输出 Hi,然后 CALL 它。
点击“运行”查看此处输出。
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
写 Swap,用 BYREF 交换 FirstNumber 和 SecondNumber。从 FirstNumber ← 1、SecondNumber ← 2 开始,输出 2,1。
点击“运行”查看此处输出。
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
只编写 PROCEDURE Reduce(BYREF Amount : INTEGER, BYVAL Discount : INTEGER)。从 Amount 中减去 Discount,但结果不能低于零。检查程序会调用它。
点击“运行”查看此处输出。