Lesson 80: By value or by reference
此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
English
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.
English
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 and 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 and 回报 the result, so the program prints n = 5, twice = 10.
点击“运行”查看此处输出。