In c programming language, there are two ways to pass the data to the function.
In the call by value, the value is not modified but in the call by reference, the value is modified.
Below is the difference between the call by value and call by reference. In the call by value, the actual arguments are passed to formal arguments so that the value is not modified, but in the call by reference, the address of actual arguments is passed to formal arguments and the value is modified.
Here is an example of the call by value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #include <stdio.h> void callByValue(int, int); /* define the function prototype */ int main() /* define main function */ { int num1 = 10; int num2 = 20; callByValue(num1, num2); printf("num1: %d, num2: %d\n", num1, num2); } void callByValue(int x, int y) { int temp; temp = x; x = y; y = temp; } |
num1: 10
num2: 20
Here is an example of the call by reference.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | #include <stdio.h> void callByReference(int*, int*); /* define the function prototype */ int main() /* define main function */ { int n1 = 10, n2 = 20; callByReference(&n1, &n2); printf("n1: %d, n2: %d\n", n1, n2); } void callByReference(int *a, int *b) { int t; t = *a; *a = *b; *b = t; } |
n1: 20
n2: 10
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.
Article Tags: call by reference, call by value, call by value and call by reference, call by value and call by reference in c, call by value and call by reference program, what is call by value and call by reference