Lesson 80: By value or by reference
Copies or the real thing?
- By value: the function gets a copy of the variable. If it changes the copy, the caller's variable stays the same.
- By reference: the function gets the variable itself (C++ writes
&before the parameter name). A change stays after the function ends.
| Pseudocode (9618) | C++ |
|---|---|
| BYVAL X : INTEGER | int x |
| BYREF X : INTEGER | int &x |
- Use by reference when the function should change the caller's variables, for example a swap. Otherwise use by value and return the answer.
In the exam
- 9618/23/M/J/24 Q7(a)(ii): Mod-F gets Par3 by value and Mod-G gets it by reference; explain the effect. Mark scheme: any change made to Par3 inside Mod-G (by reference) is reflected in the value in the calling module after Mod-G ends; any change inside Mod-F (by value) is not reflected in the calling module.
Сложность 4/5 · 280 монет + небольшой бонус за первое завершение сегодня
The two LEDs should take turns every half second: the loop switches onPin on and offPin off, then swaps the two variables. But only the green LED ever lights. swapPins gets its parameters by value: it swaps two copies. Pass them by reference with &, so the swap changes onPin и offPin.
Нажмите Запустить, чтобы увидеть результат здесь.
Сложность 3/5 · 200 монет + небольшой бонус за первое завершение сегодня
Here it is the other way round. twice gets n by reference, so it changes n itself and the program prints n = 10, twice = 10. Make twice take its parameter by value и возврат (return) the result, so the program prints n = 5, twice = 10.
Нажмите Запустить, чтобы увидеть результат здесь.