Call by value and Call by reference in C are two ways to pass arguments in a function
Lets see above one by one
Call by value
Whenever we call a function and passes the value of variable to the called function is called call by value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | #include <stdio.h> void swap(int x, int y); /* function declaration */ int main () { int a = 10; int b = 20; printf("Value of 'a' before swap= %d\n", a ); printf("Value of 'b' before swap= %d\n", b ); swap(a, b); // calling a function swap & passes the value of variable printf("Value of 'a' after swap= %d\n", a ); printf("Value of 'b' after swap= %d\n", b ); return 0; } void swap(int x, int y) // function definition to swap the values { int temp; temp = x; x = y; y = temp; return; } |
OUTPUT
1 2 3 4 | Value of 'a' before swap= 10 Value of 'b' before swap= 20 Value of 'a' after swap= 10 Value of 'b' after swap= 20 |
Call by reference
Whenever we call a function and passes the reference of variable to the called function is called call by reference.
In the call by reference, to pass the reference of the variable we use pointer.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | #include <stdio.h> void swap(int * x, int * y); /* function declaration */ int main() { int a = 10; int b = 20; printf("Value of 'a' before swap= %d\n", a); printf("Value of 'b' before swap= %d\n", b); swap( & a, & b); //call function swap and passes the reference of variable printf("Value of 'a' after swap= %d\n", a); printf("Value of 'b' after swap= %d\n", b); return 0; } void swap(int * x, int * y) // function definition to swap the values { int temp; temp = * x; * x = * y; * y = temp; return; } |
OUTPUT
1 2 3 4 | Value of 'a' before swap= 10 Value of 'b' before swap= 20 Value of 'a' after swap= 20 Value of 'b' after swap= 10 |