6

I have a trouble with references. Consider this code:

void pseudo_increase(int a){a++;}  
int main(){  
    int a = 0;
    //..
    pseudo_increase(a);
    //..
}

Here, the value of variable a will not increase as a clone or copy of it is passed and not variable itself.
Now let us consider an another example:

void true_increase(int& a){a++;}
int main(){  
    int a = 0;
    //..
    true_increase(a);
    //..
}

Here it is said value of a will increase - but why?

When true_increase(a) is called, a copy of a will be passed. It will be a different variable. Hence &a will be different from true address of a. So how is the value of a increased?

Correct me where I am wrong.

B Faley
  • 17,120
  • 43
  • 133
  • 223
T.J.
  • 1,466
  • 3
  • 19
  • 35
  • 1
    You should probably use different identifiers for the function argument and the variable being passed to it so that you don't confuse yourself even further. – AusCBloke Jan 19 '12 at 05:44
  • 1
    Passing by reference does not create a copy. It's a reference to the same variable. – jweyrich Jan 19 '12 at 05:44
  • I suggest you to learn about pointers first then about how references can reduce the pain of uninitialized objects and invalid pointers etc. Pick any of your favorite C/C++ books! – sarat Jan 19 '12 at 06:09

3 Answers3

6

Consider the following example:

int a = 1;
int &b = a;
b = 2; // this will set a to 2
printf("a = %d\n", a); //output: a = 2

Here b can be treated like an alias for a. Whatever you assign to b, will be assigned to a as well (because b is a reference to a). Passing a parameter by reference is no different:

void foo(int &b)
{
   b = 2;
}

int main()
{
    int a = 1;
    foo(a);
    printf("a = %d\n", a); //output: a = 2
    return 0;
}
B Faley
  • 17,120
  • 43
  • 133
  • 223
5

When true_increase(a) is called , copy of 'a' will be passed

That's where you're wrong. A reference to a will be made. That's what the & is for next to the parameter type. Any operation that happens to a reference is applied to the referent.

Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274
1

in your true_increase(int & a) function, what the code inside is getting is NOT A COPY of the integer value that you have specified. it is a reference to the very same memory location in which your integer value is residing in computer memory. Therefore, any changes done through that reference will happen to the actual integer you originally declared, not to a copy of it. Hence, when the function returns, any change that you did to the variable via the reference will be reflected in the original variable itself. This is the concept of passing values by reference in C++.

In the first case, as you have mentioned, a copy of the original variable is used and therefore whatever you did inside the function is not reflected in the original variable.

Izza
  • 2,389
  • 8
  • 38
  • 60