Call by Value and Call by Reference
Call by Value and Call by Reference
There are two ways to pass arguments/parameters to function calls:
-
Call by Value
-
Call by Reference
Major Difference
-
In call by value, a copy of actual arguments is passed to the function.
-
In call by reference, the location (address) of actual arguments is passed, so changes inside the function affect the original variables.
Call by Value in C
In C, all function arguments are passed by value.
-
The calling and called functions do not share memory.
-
Each function works on its own copy of variables.
-
The called function cannot directly modify variables of the calling function.
Why Call by Reference is Sometimes Needed
-
A function can return only one value using the return statement.
-
If multiple values need to be modified, call by reference is required.
-
-
If the data size is large, copying arguments:
-
Takes more time
-
Uses more memory
-
How Call by Reference Works in C
To achieve call by reference:
-
The calling function passes the address of the variable (using
&). -
The called function receives a pointer.
-
The variable is accessed using dereferencing (
*). -
Changes made through the pointer affect the original variable.
Comparison Table
| Call by Value | Call by Reference |
|---|---|
| Copy of actual arguments is passed | Address of actual arguments is passed |
| Changes in function do not affect original variables | Changes do affect original variables |
| Safer — accidental modification is impossible | Must be handled carefully to avoid unexpected changes |
Example: Call by Value
Output
Explanation:
swapByValue() only swaps local copies a and b.
Original variables n1 and n2 remain unchanged.
Example: Call by Reference
Output
Explanation:
Addresses of n1 and n2 are passed.
The function modifies the original variables using pointers.
Important Note
Arrays are passed by reference in C.
Any modification made to an array inside a function affects the original array.
Comments
Post a Comment