Functions can be invoked in two ways: Call by Value or Call by Reference. These two ways are generally differentiated by the type of values passed to them as parameters.
The parameters passed to function are called actual parameters whereas the parameters received by function are called formal parameters.
// C program to illustrate// call by value
#include
// Function Prototype
void swapx(int x, int y);
// Main function
int main()
{
int a = 10, b = 20;
// Pass by Values
swapx(a, b);
printf("a=%d b=%d\n", a, b);
return 0;
}
// Swap functions that swaps
// two values
void swapx(int x, int y)
{
int t;
t = x;
x = y;
y = t;
printf("x=%d y=%d\n", x, y);
}
Output x=20 y=10
a=10 b=20
- Call by Reference: Both the actual and formal parameters refer to the same locations, so any changes made inside the function are actually reflected in actual parameters of the caller.
// C program to illustrate// Call by Reference
#include
// Function Prototype
void swapx(int*, int*);
// Main function
int main()
{
int a = 10, b = 20;
// Pass reference
swapx(&a, &b);
printf("a=%d b=%d\n", a, b);
return 0;
}
// Function to swap two variables
// by references
void swapx(int* x, int* y)
{
int t;
t = *x;
*x = *y;
*y = t;
printf("x=%d y=%d\n",x,y);
}
Output:x=20 y=10
a=20 b=10