Home > Back-end >  Why the second is right, what's the use of this symbol &
Why the second is right, what's the use of this symbol &

Time:09-15


Swap (int x, int y)
{
Int temp=x;
X=y;
Y=temp;
}




SwapByRef (int & amp; X, int & amp; Y)
{
Int temp=x;
X=y;
Y=temp;
}


Void main ()
{
Int x=1, y=2;
Swap (x, y);
SwapByRef (x, y);
}

CodePudding user response:

& Refers to
The second is reference, variable in a function is equivalent to a variable outside a function (function stack is different, but the address is the same), so to the change of the function, function is the change of the outside
The value of the first kind is passed, the function of variables and functions has nothing to do (function stack is different, have different address), so the function change won't affect the variable outside a function,

CodePudding user response:

That is the basic grammar, c + + reference, and pointer is essentially the same, so you can modify the parameters,

In c + +, expanded the & amp; Meaning, in addition to retain the pick up address, as well as reference,

CodePudding user response:

 swapByRef (int & amp; X, int & amp; Y) 
{
Int temp=x;
X=y;
Y=temp;
}


Functional equivalence:

 swapByRef (int * x, int * y) 
{
Int temp=* x;
* x=* y;
* y=temp;
}

CodePudding user response:

& Is take the address sign,
Suggested that the pass have a look at the value and the difference between the reference,
  • Related