There are two ways in which the argument can be passed through a function in C Programming.
- Call by Value
- Call by Reference
Call by Value in C.
In this method, the actual argument is copied to the formal parameter of the function. Hence any operation performed on the argument does not affect the actual parameters. By default, C programming uses call by value to pass arguments.
Since the actual parameter is copied to formal parameters, different memory is allocated for both parameters.
Example: Swap the values of two variables in C Programming:
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 30 31 | #include <stdio.h> //declaration void swap(int, int); int main() { int a = 100; int b = 500; printf("Before swapping the value of a = %d", a); printf("\nBefore swapping the value of b = %d\n", b); //Calling a function swap(a, b); printf("\nAfter swapping the value of a = %d", a); printf("\nAfter swapping the value of b = %d", b); } void swap(int a, int b) { int temp; temp = a; a = b; b = temp; //The values interchange here inside function //foraml parameters printf("\nAfter swapping values of a and b inside function: a = %d, b = %d\n", a, b); } |
The output of call by Value:
1 2 3 4 5 6 7 | Before swapping the value of a = 100 Before swapping the value of b = 500 After swapping values of a and b inside function: a = 500, b = 100 After swapping the value of a = 100 After swapping the value of b = 500 |
Call by Reference.
Unlike call by value method, here the address of the actual parameter is passed to a formal parameter rather than value. Hence any operation performed on formal parameters affects the value of actual parameters.
The memory allocation for both actual and formal parameters are same in this method.
Example: Swap the values of two variables in C Programming:
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 30 31 | #include <stdio.h> //declaration void swap(int *, int *); int main() { int a = 100; int b = 500; printf("Before swapping the value of a = %d", a); printf("\nBefore swapping the value of b = %d\n", b); //Calling a function swap(&a, &b); printf("\nAfter swapping the value of a = %d", a); printf("\nAfter swapping the value of b = %d", b); } void swap(int *a, int *b) { int temp; temp = *a; *a = *b; *b = temp; //The values interchange here inside function //foraml parameters printf("\nAfter swapping values of a and b inside function: a = %d, b = %d\n", *a, *b); } |
The output of call by Reference:
1 2 3 4 5 6 7 | Before swapping the value of a = 100 Before swapping the value of b = 500 After swapping values of a and b inside function: a = 500, b = 100 After swapping the value of a = 100 After swapping the value of b = 500 |