Functions
Q) What is functions ?
-> Functions is a piece of code which perform a specific task.
Parameter Passing:-
(a) pass by value (both in c/c++)
(b) pass by address (both in c/c++)
(c) pass by reference ( in c++ only available)
Note: Grouping of data is structure but Grouping of instruction is a function.
Parameter Passing method
(a) call by value
//Swapping Program
void swap(int x, int y){
int temp;
temp=x;
x=y;
y=temp;
}
int main(){
int a,b;
a=10;
b=20:
swap(a,b);
output
printf("%d%d",a,b);
return 0;
}
10 20
Conclusion: we see that formal parameter are modified (x,y,temp) variable But actual parameter are remains same(a,b) variable.
so. swapping is done inside the swap function they are not reflected in actual parameter(a,b).
(ii) Call By Address
Note: it is more useful.
using call by address addresses of actual parameter are pass to formal parameters and formal parameter must pe pointer.
Any change done inside function will modify actual parameter
//simple code
void swap (int *x, int *y){
int temp;
temp= *x;
*x=*y;
*y=temp;
}
void main()
{
int a,b;
a=10;
b=20:
swap(&a,&b);
print("%d,%d",a,b);
}
output:
20,10
Conclusion : Call by address is suitable mechanism for modifying the actual parameter.
(iii) Call by references: it is nothing but alias or another name(nickname) of other variable.
-> This is not a part of c language only supported in c++ and it is very useful and powerful feature
Note: references doesn’t take any extra memory because it is just another name
//simple program to understand it better
void swap(int &x, int &y){
int temp;
temp=x;
x=y;
y=temp;
}
int main(){
int a,b;
a=10;
b=20:
swap(a,b);
output
printf("%d%d",a,b);
return 0;
}
10 20
Conclusion: these formal parameter (&x,&y) are manipulated actual parameter actual parameter (a,b) data are changed/modified.
you can see in memory swap s not a separate function it has become a part of main function and there is only one activation record.