The variables that accept the arguments values can only be used in functions. These variables are also called as
formal parameters
of the function.
Inside of the function formal parameters behaves like other local variables and are created when entered into the function and destroys when exits the function.
Any Functions in C normally accepts the argument and it gives back a return value to the calling Program.So, there establishes two-way Communication between calling function and called function.
There are two ways to pass the arguments while calling a function from a program.They are :
- Call by value.
- Call by reference.
By default, all functions are passed by "call by value". The value of the variable is passed as a parameter. Actual value cannot be modified by using the derived parameter i.e formal parameter.Both are given different memories.
[c]
#include<stdio.h>
#include<conio.h>
int swap(int , int); // Declaration of function
main( )
{
int a = 10, b = 20 ; // call by value
swap(a,b); // a and b are actual parameters
printf ( "\n Before Swapping \n a = %d b = %d \n", a, b ) ;
getch();
}
int swap( int x, int y ) // x and y are formal parameters
{
int t ;
t = x ;
x = y ;
y = t ;
printf ("\n\nAfter swapping \n x = %d y = %d", x, y ) ;
}[/c]
Output:
[c]
After swapping
x = 20 y = 10
Before Swapping
a = 10 b = 20
[/c]
By using call by reference,address of the variable is passed as a parameter. Actual parameter can be modified by using the derived parameter i.e formal parameter.Both are given same memories.
[c]
#include<stdio.h>
#include<conio.h>
int main( )
{
int num1 = 35, num2 = 45 ;
printf("Before swapping: num1 value is %d and num2 value is %d", num1, num2);
/*calling swap function*/
swapnum ( &num1, &num2 );
printf("\nAfter swapping: num1 value is %d and num2 value is %d", num1, num2);
}
swapnum ( int *var1, int *var2 )
{
int tempnum ;
tempnum = *var1 ;
*var1 = *var2 ;
*var2 = tempnum ;
}[/c]
Output:
[c]
Before swapping: num1 value is 35 and num2 value is 45
After swapping: num1 value is 45 and num2 value is 35
[/c]