1

I understand the pointer concept (int*), but I cannot understand int& because they give the same result. What does int &data exactly mean?

void add1(int *data){
  (*data)++;
}

void add2(int &data){
  data++;
}

int main()
{
  int i=0;

  add1(&i);
  printf ("value i = %d\n",i) // show 1

  add2(i);
  printf ("value i = %d\n",i); // show 2

  return 0;
}
Naive Developer
  • 700
  • 1
  • 9
  • 17

1 Answers1

6

The function signature:

void add2(int &data)

is the pass-by-reference facility in C++. It's a way to allow the function to change the value passed in and have that change reflected back to the caller. In C, upon which C++ was originally based, all paramaters are pass-by-value, meaning the functions get a local copy which, if changed, does not affect the original value passed in.

As an aside, pass by reference is probably the one facility I'd most like to see added to C (not full-blown C++ references, just in the function calls) since I'm pretty certain 42% of all C questions here on SO have to do with pointers :-)

The way to do pass-by-reference in C and C++ can be seen in the lines below. The first is the right way to do it in C++, and the second is the "pointer gymnastics" poor C developers have to go through to get the same effect:

void FortyTwo(int &x) { x = 42; }     // Call with FortyTwo(variable);
void FortyTwo(int *pX) { *pX = 42; }  // Call with FortyTwo(&variable);

In the latter, the pointer is passed by value but you can use that pointer to get at (and change) the data it points to. In C++, you should, as much as possible, avoid passing the pointers to values you want to change since that's one of the reasons references were added to C++ in the first place. It also makes your code easier to understand if you don't have to pepper it with pointer dereferences.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953