There are two different methods for passing a variable in function as a parameter:
1.Call by value: we pass copy of actual variables in function as a parameter. Any changes on parameters inside the function will not effect the actual variable.
#include<stdio.h>
void main(){
int a=5,b=10;
change(a,b);
printf("%d %d",a,b);
}
void change(int a,int b){
a=a+b;
b=a-b;
a=a-b;
b=a-b;
a=a-b;
}
Output: 5 10
2.Call by reference: we pass memory address of actual variables in function as a parameter. Hence if we make any changes on parameters inside the function will effect the actual variable.
#include<stdio.h>
int main(){
int a=5,b=10;
change(&a,&b);
printf("%d %d",a,b);
return 0;
}
void swap(int *a,int *b){
int *temp;
*temp =*a;
*a=*b;
*b=*temp;
}
Output: 10 5
0 comments:
Post a Comment