When you pass a variable to a function, does the function work on your variable or on a copy? In C, the answer is always a copy. This explains a famous puzzle: a swap function that swaps nothing.
What call by value means
In call by value, the formal arguments are new local variables of the called function. They are created when the function is called, initialised with the values of the actual arguments, and destroyed when the function returns.
Safe: a function cannot accidentally change the caller’s variables
A function cannot change the caller’s variables even when that is wanted (as in swap)
Simple to understand and reason about
Copying large data items takes extra memory and time
Any expression can be an argument: square(x + 1), square(5)
Only one result can come back, through return
How the problem is solved in C
To let a function change the caller’s variable, the caller passes the variable’s address, and the function uses that address to reach the original. This needs pointers (Unit 7), where the working swap is written as swap(&x, &y). It is the same mechanism by which a function can modify an array passed to it (Unit 4).
Key takeaways
In call by value, formal arguments are copies of the actual arguments.
Changes to parameters are lost when the function returns.
It is safe and simple, but a function cannot directly modify the caller’s variables.
Passing addresses with pointers (Unit 7) gives the effect of call by reference.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
For void change(int a) { a = a * 2; printf("%d ", a); } and int main(void) { int v = 7; change(v); printf("%d\n", v); return 0; }, give the output and explain it.
Show worked answer
The output is 14 7. When change(v) is called, the value 7 is copied into the parameter a. Inside the function a becomes 14 and is printed. When the function returns, a is destroyed. The variable v in main was never modified, so the second printf prints 7.
MCA Online notes are made for reading on screen. Open https://mcastudy.online/mcs-201/functions/call-by-value/ to read this page.