Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are values copied when passed as arguments?

Tags:

c++

So when passing arguments by value, the value(s) is copied to the function’s parameter(s), but how does it work? Are the parameters just declared as regular variables and assigned the values passed as arguments? Like this:

int getx(int z, int x)
{
int a = z+x;
return a;
}

int main()
{
int q = 2;
int w = 55;
int xx = getx(w, 2);
return 0;
}

If so, why would you call this to copy the value? Isn’t the parameter variable just assigned the value of the variable x? What is copied then?


1 Answers

Short and fun answer: You should think of variables as boxes that hold a toy. if a function takes a parameter by vaule and you call the function, you are just telling the function what toy you have in your box. It goes and gets its own toy that is exactly like the one you have (but not your toy), and plays with it. So you don't care what it does to the toy inside the function, cause it isn't your actual toy. When you pass by reference, you are actually giving the function the toy out of your own box, and it plays with your toy instead of getting its own.

A longer more indepth-ish answer: It means that when you call int xx = getx(w, 2); in your main function inside of your getx function you are going to use a chunk of data that has the same bits in it as the chunks of data you passed. but they are not the same chunk of data. this means that z is just a copy of the info that was in w when you called the function.

Assume you wrote getx like this (where z is passed in by value)

int getx(int z, int x) {
    int a = z + x;
    z = z + 1;
    return a;
}

In this case, after you call this function inside of main (getx(w, 2)) a copy of w went in as 55, and w comes out as 55

In contrast, if you were to have this:

int getx(int& z, int x) {
    int a = z + x;
    z = z + 1;
    return a;
}

and then called it in the like you do in your main

int main()
{
    int q = 2;
    int w = 55;
    int xx = getx(w, 2);
    return 0;
}

In this case, z is passed in by reference (notice the use of int& instead of int). Which means, you are not using a copy of w's data, you will actually use the real w's data inside of getx. so in this case in your main function, after you call getx(w, 2) w (not a copy) goes in as 55, so w comes out as 56

P.S. Passing by reference is, in my opinion, usually bad practice. You can't tell just by reading getx(w, 2) that w is going to come out differently than it went in.

like image 182
MBurnham Avatar answered Feb 02 '26 04:02

MBurnham