1

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;
}
Pavan Kumar
  • 77
  • 1
  • 6
  • possible duplicate of [Pass by reference in C](http://stackoverflow.com/questions/1919718/pass-by-reference-in-c) – ahoffner May 20 '15 at 02:20

1 Answers1

1

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.