Procedimientos y 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.
Dificultad 2/5 · 140 monedas + un pequeño bono en el primer intento de hoy
Escribe un procedimiento Greet sin parámetros que emita Hi, luego CALL it.
Haz clic en Ejecutar para ver la salida aquí.
Dificultad 2/5 · 140 monedas + un pequeño bono en el primer intento de hoy
Escribe Swap para que BYREF intercambie FirstNumber y SecondNumber. Comienza con FirstNumber ← 1 y SecondNumber ← 2, y emite 2,1.
Haz clic en Ejecutar para ver la salida aquí.
Dificultad 3/5 · 200 monedas + un pequeño bono en el primer intento de hoy
Escriba solo PROCEDURE Reduce(BYREF Amount : INTEGER, BYVAL Discount : INTEGER). Reduzca Amount por Discount, pero nunca por debajo de cero. El validador lo llamará.
Haz clic en Ejecutar para ver la salida aquí.