Процедуры и BYREF
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.
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.
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.
PROCEDURE Show(Number : INTEGER)
Number ← Number + 1
OUTPUT Number
ENDPROCEDURE
DECLARE FirstNumber : INTEGER
FirstNumber ← 5
CALL Show(FirstNumber)
OUTPUT FirstNumber
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.
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.
Common mistakes
CALLbefore a procedure. NeverCALLa function.- IGCSE 0478 has no
BYREF. On that paper every parameter is a copy.
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.
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, но не допускайте значения ниже нуля. Вызов процедуры проверяет автоматический проверщик.
Нажмите Запустить, чтобы увидеть результат здесь.