difference between these ways

Hi guys I'm wondering whats the differences between these pieces of code in one I'm using the * to pass by ref a and in the other I'm using & to pass by ref yet I still get the same result,whats the difference and why are the results the same?

Thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
  #include <iostream>

using namespace std;

void val(int x);
void reff(int &x);

int main()
{
   int a = 13;
   int b = 13;

   cout << a << endl;
   cout << b << endl;

   val(a);
   reff(b);

   cout << a << endl;
   cout << b << endl;


}



void val(int x){

    x = 23;

}


void reff(int &x){

   x = 30;

}



and

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>

using namespace std;

void val(int x);
void reff(int *x);

int main()
{
   int a = 13;
   int b = 13;

   cout << a << endl;
   cout << b << endl;

   val(a);
   reff(&b);

   cout << a << endl;
   cout << b << endl;


}



void val(int x){

    x = 23;

}


void reff(int *x){

   *x = 30;

}
they both do the same , pass by reference and pointer , as you can see pass by value does not do much out of its scope. the difference is that you wont be able to change the address of the reference , the pointer you get the address but you can change it , to access its data you use the * operator. Use & or * depend on your cases. Both are valid.
Topic archived. No new replies allowed.