Explain in details on the calling a function by value and by reference with a perfect example in C programming for each.

Call by Value
If data is passed by value, the data is copied from the variable used in for example main() to a variable used by the function. So if the data passed (that is stored in the function variable) is modified inside the function, the value is only changed in the variable used inside the function. Let’s take a look at a call by value example:
 
#include <stdio.h>
void call_by_value(int x) {
       printf("Inside call_by_value x = %d before adding 10.\n", x);
       x += 10;
       printf("Inside call_by_value x = %d after adding 10.\n", x);
} 
int main() {
       int a=10;
       printf("a = %d before function call_by_value.\n", a);
       call_by_value(a);
       printf("a = %d after function call_by_value.\n", a);
       return 0;
}

Call by Reference
If data is passed by reference, a pointer to the data is copied instead of the actual variable as is done in a call by value. Because a pointer is copied, if the value at that pointers address is changed in the function, the value is also changed in main(). Let’s take a look at a code example:
 
#include <stdio.h>
void call_by_reference(int *y) {
       printf("Inside call_by_reference y = %d before adding 10.\n", *y);
       (*y) += 10;
       printf("Inside call_by_reference y = %d after adding 10.\n", *y);
}
int main() {
       int b=10;
       printf("b = %d before function call_by_reference.\n", b);
       call_by_reference(&b);
       printf("b = %d after function call_by_reference.\n", b); 
       return 0;
}

0 Comment "Explain in details on the calling a function by value and by reference with a perfect example in C programming for each. "

Post a Comment