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;
}
1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.