Swapping variables with a function doesn't affect the call site

限于喜欢 提交于 2020-01-11 12:05:23

问题


A few lessons ago I learned about variables, and got a question in my homework about swapping two numbers - I used a third variable to solve this question.

The solution looked somewhat like this:

#include <stdio.h>

int main(void) {
    int x, y;
    scanf("%d %d", &x, &y);

    // swappring the values

    int temp = x;
    x = y;
    y = temp;

    printf("X is now %d and Y is now %d", x, y);
}

Now I'm learning about functions, and I wanted to try and solve the previous question with a helper swap function.

This is the code I've written:

#include <stdio.h>

void swap(int x, int y) {
    int temp = x;
    x = y;
    y = temp;
}

int main(void) {
    int a = 3, b = 4;
    swap(a, b);

    printf("%d %d\n", a, b);
}

I don't know why, but the output is still 3 4 even though I changed the value inside the swap() function.

Why is this happening?


回答1:


Pass address of x and y as arguments to function. Right now they are local variables, changes are not made to original variables .

Do as follows-

void swap(int *x,int *y){
 /*            dereference pointers and  swap    */
 int temp = *x;
 *x = *y;
 *y = temp;
}

And call in main like this -

swap(&x,&y);



回答2:


What you are doing is passing parameter by value. It means that during the function call, copies of parameters are created. So inside the function you are working on copies of actual variables.

Instead you need to pass it as a reference. Please read more about pass-by-value vs pass-by-reference.

#include <stdio.h>
void swap(int& x,int& y)    //Instead of passing by value just pass by reference
{
    int temp=x;
    x=y;
    t=yemp;
}
int main() {
    int a=3,b=4;
    swap(a,b);
    printf("%d %d\n",a,b);

    return 0;
}

EDIT: C does not have references. Above code will work in c++ instead. To make in work in C, just use pointers and de-reference it inside the function.



来源:https://stackoverflow.com/questions/33710633/swapping-variables-with-a-function-doesnt-affect-the-call-site

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!