0
What is the difference between void swap(int &x,int &y) and void swap(int x,int y) ?? Diffrence between int &x and int x
6 ответов
+ 6
@kunal: As I said, int &x defines a reference to an integer variable, it doesn't return anything and has nothing to do with & as the address-of operator.
Here is an example:
#include <iostream>
using namespace std;
void func(int &x) {
x = 42;
}
int main(){
int ans = 54;
func(ans);
cout << ans; //prints 42
return 0;
}
As you can see from the example, the change made to ans in the func() function persists past the function call. The argument is the variable ans rather than its value.
Also, since func()'s parameter is a reference, you can't give it a value as argument. func(54) would give you an error for example.
Here is another example using a reference, without it being a parameter of a function:
int foo = 1;
int &bar = foo;
bar = 2;
cout << foo; //prints 2
+ 4
@kunal: int &x defines a variable named x that is a reference to another variable (in the given example, to a variable given as argument to the function). It is a perfectly valid name.
Furthermore, & here is NOT the address-of operator, it is just part of the definition of a reference, much like when typing int *x you merely defines a pointer and * here is not the dereferencing operator.
Also, variables are stored in the stack, not the heap.
+ 3
In void swap(int &x, int &y), the parameters are references to variables, and any change done to those in the function will persist. This is not the case in void swap(int x,int y), where the arguments are merely passed by value.
0
Firstly , the above function parameters (int &x, int &y) not exist bcoz the variable naming always starts with the letter of alphabet or an underscore..
or if u want the difference been them. is just. &x has the address of the variable x and x contains the value saved in the heap.
0
ohh I understood what u mean. but I said value saved in heap of variable x. I know variables always stored in stack.
and I m also confused with how &x works in the parameter of the function. is it returns the value or address of variable x
0
Nothing is as simple as that,
When func( int &x) called , and "ans" is passed as actual parameter to function as func(ans),then
int &x means- It is saying that hey " ans" I am having the same address as you,
now since both i.e., x in function as &x and actual parameter ans both pointing to same address in memory, so any changes made to x would reflect in ans as well.
This also relates the point that whenever 54 directly passed to function as func(54), it will give error as 54 doesn't have any address in memory.
Hope! it helps.