C Call by Value and Call by Reference
There are two ways to pass arguments to a function.
Call by value
A copy of the value is sent. Changes inside the function do not change the original variables. C uses this way by default.
#include <stdio.h>
void swap(int a, int b) {
int t = a;
a = b;
b = t;
}
int main(void) {
int x = 10, y = 20;
swap(x, y);
printf("x=%d y=%d\n", x, y);
return 0;
}
Output:
Output of the above program is
x=10 y=20
The values did not swap, because the function worked on copies.
Call by reference (using pointers)
We send the address of the variables with &. The function uses pointers (*) to change the original values.
#include <stdio.h>
void swap(int *a, int *b) {
int t = *a;
*a = *b;
*b = t;
}
int main(void) {
int x = 10, y = 20;
swap(&x, &y);
printf("x=%d y=%d\n", x, y);
return 0;
}
Output:
Output of the above program is
x=20 y=10
Difference
| Point | Call by value | Call by reference |
|---|---|---|
| What is sent | Copy of the value | Address of the variable |
| Original changed? | No | Yes |
| Memory | Extra copy is made | No copy of the data |
Note:
Strictly speaking, C has only call by value. Passing a pointer is also a value (the address), but it gives the same result as call by reference. Learn more in Pointers.
Next: C Recursion.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |