Originally Posted on SeedBx
Welcome to the fourth part of the Gentle Introduction to C series. As
said before this series aims to provide you a brief introduction to C language.
In this part we will be looking at call by value and call by reference.
Before talking about call by value and call by reference
let’s get some more terminologies under our belt.
Function Call : It is a request made by the program by using
the function name and a list of parameters (if any) enclosed in braces.
Formal Parameters :
These are the parameters which are defined in the function.
Actual Parameters : These are the parameters that the caller location passes to the function.
Interesting Fact : C is case-sensitive
Call By Value
Call by Value is a function calling technique in which the formal parameters and actual parameters are different independent variables, more so the formal parameters are separate variables which share the same value. Internally what happens is when a function is called by value the values of the actual parameters are copied to the formal parameters (dummy variables). As the formal parameters and actual parameters are different, any changes made to formal parameters are not reflected in actual parameters.
Example-
Code :
#include<stdio.h>
void callByValue(int a)
{
a=3;
printf("Value of Formal Parameter =
%d\n", a);
}
int main()
{
int a;
a=2;
callByValue(a);
printf("Value of Actual Parameter =
%d", a);
return 0;
}
Output :
Value of Formal Parameter = 3
Value of Actual Parameter = 2
As
you can notice above, the value of 'a' in the main() function is not affected
by the change in the value of 'a' in callByValue() function.
Call By Reference
Call by reference is a function calling technique in which the
formal parameters and actual parameters are actually identical variables, i.e.
they share the same memory location internally. Call by reference can be
initiated by passing either pointers to the variable or passing reference to
the variable. As the formal and actual parameter share the same memory
location, any changes to the formal parameters is actually reflected in the
actual parameters.
Example-
Code :
#include<stdio.h>
void callByReference(int &a)
{
a=3;
printf("Value of Formal Parameter =
%d\n", a);
}
int main()
{
int a;
a=2;
callByReference(a);
printf("Value of Actual Parameter =
%d", a);
return 0;
}
Output :
Value of Formal Parameter = 3
Value of Actual Parameter = 3
As you can notice above, the value of 'a' in the main() function is affected by the change in the value of 'a' in callByReference() function.
Both of these function calling techniques have their fair share of
uses in actual applications, however the calling technique to be used totally
depends on the use case.
As always your suggestions are welcome.
Do comment out what are some interesting ways in which you use these
calling techniques.
Also See : Function, main(),
No comments:
Post a Comment