There are two ways that a C function can be called from a program. They are,
- Call by value
- Call by reference
1. Call by value:
- In call by value method, the value of the variable is passed to the function as parameter.
- The value of the actual parameter cannot be modified by formal parameter.
- Different Memory is allocated for both actual and formal parameters. Because, value of actual parameter is copied to formal parameter.
Note:
- Actual parameter – This is the argument which is used in function call.
- Formal parameter – This is the argument which is used in function definition
//Example of Call by Value
#include <stdio.h>
#include<conio.h>
void swapval(int a,int b);
void main()
{
int a,b;
clrscr();
a=10;
b=20;
printf(“\nValues before swap a=%d and b=%d”,a,b);
swapval(a,b);
getch();
}
void swapval(int a,int b)
{
int tmp;
tmp=a;
a=b;
b=tmp;
printf(“\nValues after swap a=%d and b=%d”,a,b);
}
|
2. Call by reference:
- In call by reference method, the address of the variable is passed to the function as parameter.
- The value of the actual parameter can be modified by formal parameter.
- Same memory is used for both actual and formal parameters since only address is used by both parameters.
//Example of Call by Reference
#include <stdio.h>
#include<conio.h>
void swapval(int *a,int *b);
void main()
{
int a,b;
clrscr();
a=10;
b=20;
printf(“\nValues before swap a=%d and b=%d”,a,b);
swapval(&a,&b);
getch();
}
void swapval(int *a,int *b)
{
int tmp;
tmp=*a;
*a=*b;
*b=tmp;
printf(“\nValues after swap a=%d and b=%d”,*a,*b);
}
|
0 comments:
Post a Comment