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 و 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 و إرجاع the result, so the program prints n = 5, twice = 10.
اضغط تشغيل لرؤية المخرجات هنا.