Introduction
There are several techniques for passing parameter data into and out of methods and functions. Assume that function B() is called from another function A. (). In this scenario, A is referred to as the "caller function," whereas B is referred to as the "called function or callee function." Furthermore, the arguments that A sends to B are referred to as actual arguments, whereas B's parameters are referred to as formal arguments. When a function is called, the calling function must send certain values to the called functions.
There are two ways by which we can pass the parameters to the functions:
- Call by value
-
Call by reference
Also see: C Static Function, Difference between argument and parameter
Call by value
- The variables' values are supplied to the called function by the calling function.
- If any parameter value in the called function has to be changed, the change will be reflected solely in the called function.
-
This occurs because all modifications are done to the copy of the variables rather than the originals.
This technique employs in-mode semantics. Changes to formal parameters are not returned to the caller. Any changes to the formal parameter variable within the called function or method affect just the separate storage location and are not reflected in the real parameter in the calling environment. This approach is also known as call by value.
#include <stdio.h>
void funExample(int a, int b)
{
a += b;
printf("In func, a = %d b = %d\n", a, b);
}
int main(void)
{
int x = 5, y = 7;
funExample(x, y);
printf("In main, x = %d y = %d\n", x, y);
return 0;
}
Output:
In funExample, a = 12 b = 7
In main, x = 5 y = 7
“Also See, procedure call in compiler design“ and Short int in C Programming
Call by reference
- The addresses of the variables are given from the calling function to the called function in this case.
- The address used within the function is used to obtain the parameter used in the call.
- Any modifications made to the parameters have an effect on the passed argument.
-
Argument pointers are supplied to functions exactly like any other value when passing a value to a reference.
This method employs in/out-mode semantics. Changes to formal parameters are returned to the caller through parameter passing. Any changes to the formal parameter are reflected in the calling environment because the formal parameter obtains a reference (or pointer) to the real data. This approach is also known as a call-by-reference method. This approach is both time and space-efficient.
#include <stdio.h>
void swapNum(int* i, int* j)
{
int temp = *i;
*i = *j;
*j = temp;
}
int main(void)
{
int a = 15, b = 100;
swapNum(&a, &b);
printf("a is %d and b is %d\n", a, b);
return 0;
}
Output:
a is 100 and b is 15
You can also read about C dynamic array.