Reputation: 77
iam new to c programming and written a function to swap two numbers.the problem is that inside swap function variables are getting updated correctly but the global variables a and b are not changing.Please help me with any misconception I have.Thanks for the help.
int main(){
int a = 2; int b = 3;
void swap(int a , int b){
int c= a;
a = b;
b = c;
}
swap(a,b);
printf("%d\n",a);
printf("%d\n",b);
return 0;
}
Upvotes: 1
Views: 932
Reputation: 96
In C, primitive variables are passed by value, not by reference. When the swap method is called, the a
and b
parameters in the swap method are not the same a
and b
as in the main() method. Only the values of a
and b
are passed into the method. So while in the swap method, a and b are swapped, but the a
and b
in main are not actually altered.
What you need to do is pass by reference. An example of pass by reference is here.
Upvotes: 1