Hàm con và 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.
Độ khó 2/5 · 140 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
Viết một hàm con Greet không có tham số nào nhưng xuất ra Hi, sau đó gọi CALL nó.
Nhấn Chạy để xem kết quả ở đây.
Độ khó 2/5 · 140 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
Viết Swap sao cho BYREF hoán đổi FirstNumber và SecondNumber. Bắt đầu từ FirstNumber ← 1 và SecondNumber ← 2, và xuất 2,1.
Nhấn Chạy để xem kết quả ở đây.
Độ khó 3/5 · 200 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
Chỉ viết PROCEDURE Reduce(BYREF Amount : INTEGER, BYVAL Discount : INTEGER). Giảm Amount đi Discount, nhưng không được nhỏ hơn không. Bộ kiểm tra sẽ gọi hàm này.
Nhấn Chạy để xem kết quả ở đây.