-1

I found these two different sources, but they do the exact same thing. I was wondering if there is a difference or not but I couldn't figure it out.

Can anyone tell me the difference and when should I use which?

this is the first one:

void function1(int *x) {
    *x = 100;
}

int main() {
    int var1 = 10;

    function1(&var1);
    cout << var1 << endl;
}

and this is the second one:

void function2(int &x) {
    x = 100;
}

int main() {
    int var2 = 10;

    function2(var2);
    cout << var2 << endl;
}
Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
SSLukeY
  • 21
  • 5

2 Answers2

2

int *x is a pointer whereas int &x is a reference. Probably the biggest difference is that you can't change where reference is pointing to.

Jan Korous
  • 666
  • 4
  • 11
0

The first is a pointer, the second is a reference. The ideas have some similarities, but there are also differences.

A pointer is a C and C++ mechanism and a bit more "pure" but gives you more posibilies for advanced concepts like pointer arithmetics. References are C++ only and are more safe and more implicit, as a reference is used with the same syntax as a normal varible while using the referenced one. A pointer is more explicit if you want to use or change its value, as you have to explicitely dereference it using *var, and explicitely have obtain it.

sim
  • 1,148
  • 2
  • 9
  • 18