sign

i cant see any difference between these codes
what really is the use of ampersand sign in function inside parameter?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;
void sum(int a,int b,int &r)// code works well
{
r=a+b;

}
int main()
{
int w, q,x;
    cout<<"Enter two arguments separated by space ";
   cin>>w>>q;
   sum(w,q,x);
cout<<x;
}

the second
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;
void sum(int &a,int &b,int &r)//3 ampersand still works well
{
r=a+b;

}
int main()
{
int w, q,x;
    cout<<"Enter two arguments separated by space ";
   cin>>w>>q;
   sum(w,q,x);
cout<<x;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;
void sum(int a,int b,int r)//wors well
{
r=a+b;

}
int main()
{
int w, q,x;
    cout<<"Enter two arguments separated by space ";
   cin>>w>>q;
   sum(w,q,x);
cout<<x;
}
Last edited on
1
2
3
// code works well
//3 ampersand still works well
//no ampersand works well 


What do you consider as working well?
I really do not know >.<
i dont see any diff between first one and second one
The third snippet shouldn't work.
Look up references / pass by value / pass by reference.
& means pass by reference.

In fact, what happens is, a copy of the address of the variable is passed instead of a copy of the variable itself.

The effect is the value in the variable is changed in main, when modified in sum. So you ought to see difference output in example 3. That lead me to ask why you think that was ok.
There are two ways of passing something to a function. One is pass-by-value, the second is pass-by-reference. Whenever you pass something by value, the compiler makes a copy of the value you pass to the param. When the function returns, the original value that was passed in the argument remains the same. however, if you pass by reference, the compiler knows you want that argument to be changed by the function, so you pass in a reference to the variable as the argument.

http://www.learncpp.com/cpp-tutorial/73-passing-arguments-by-reference/
:)
Topic archived. No new replies allowed.