Call by value — Pseudocode Aptitude Question
Call by value: Parameters are passed by value. What is printed, in order? Answer and worked solution on CodeKairo.
- Topic: Pseudocode
- Section: Programming MCQs
- Difficulty: Medium
- Time target: 75 seconds
Question
Parameters are passed by value. What is printed, in order?
Function Change(Integer x)
Set x = x * 3
Print x
End Function
Integer a
Set a = 4
Change(a)
Print aOptions
- 4 4
- 4 12
- 12 4
- 12 12
Show the answer and the worked solution
Correct answer: C. 12 4
Worked solution
- Change receives a copy of a, so x starts at 4 and becomes 4 * 3 = 12.
- The function prints 12.
- The assignment touched only the copy, so a in the caller is still 4 and the second print shows 4, making the whole output 12 4.
Answer: 12 4.
The idea
Call by value copies the argument into the parameter. Anything the callee assigns to that parameter dies with the call, so the caller's variable is untouched.
Shortcut. The first number comes from inside Change and must be 12, leaving "12 4" or "12 12"; by value, a is untouched, so 12 4.
Common trap. "12 12" treats x as another name for a, as call by reference would; by value, the tripling dies with the copy.