When we call a function and pass the variable / parameter in the function, when passing the address of the actual arguments from the calling function, that's why it is called call by reference.
In the call by reference inside the function, we use the address of the actual arguments, this means that when is a change in the parameter, it will be affected the passed argument.
// Example 1
#include <stdio.h>
void changeValue(int *a);
int main() {
int x = 40;
// Before Calling the Function
printf("\nValue of x : %d", x);
changeValue(&x);
// After Calling the Function
printf("\nValue of x : %d", x);
return 0;
}
void changeValue(int *a){
// Inside the function
printf("\nInside the function Value of a Before perform some operation : %d", *a);
*a = *a + 20;
printf("\nInside the function value of a after perform operation : %d", *a);
}
/*
Value of x : 40
Inside the function Value of a Before perform some operation : 40
Inside the function value of a after perform operation : 60
Value of x : 60
*/
// Example 2
#include <stdio.h>
void swap(int *a, int *b);
int main() {
int x = 40, y = 60;
// Before Calling the Function
printf("\nValue of x : %d and y : %d", x, y);
swap(&x, &y);
// After Calling the Function
printf("\nValue of x : %d and y : %d", x, y);
return 0;
}
void swap(int *a, int *b){
// Inside the function
printf("\nInside the function Value of a : %d and b : %d Before perform some operation", *a, *b);
int temp = *a;
*a = *b;
*b = temp;
printf("\nInside the function value of a : %d and b : %d after perform operation", *a, *b);
}
/*
Value of x : 40 and y : 60
Inside the function Value of a : 40 and b : 60 Before perform some operation
Inside the function value of a : 60 and b : 40 after perform operation
Value of x : 60 and y : 40
*/
Comments
Oops!