[try Beta version]
Not logged in

 
references

Jun 3, 2015 at 12:27am
wht are references for? From their definition as another name to a variable they seem totally useless. What do people use it usually for?
Jun 3, 2015 at 1:18am
Yes a reference is another name for a variable.
If x is a reference to y, modifying x will modify y.

e.g
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
//x is copied to a new variable
//so changes to this x dont affect the original x
void modify_value(int x)
{
    x = x + 1;
}
//reference to the original x
//changes to this x affect the original x because a reference and a variable are the same
void modify_ref(int &x)
{
    x = x + 1;
}
int main()
{

    int x = 3;
    int &ref_x = x;


    modify_value(x);
    cout << x << endl;   //x = 3

    modify_ref(ref_x);
    cout << x << endl;  //x = 4
}


You may have noticed similarity with pointers.
1
2
3
4
5
//changes to this x affect the original x.
void modify_pointer(int *x)
{
    *x = *x + 1;
}


An advantage of references over pointers is safety.
A reference would always be initialized before being used or passed to a function.
That is not the case with a pointer as modify_pointer(NULL) is valid;

http://www.cprogramming.com/tutorial/references.html
Jun 3, 2015 at 7:53am
From their definition as another name to a variable they seem totally useless.

They are quite useless when used locally in the same function as the referenced variable is defined. References are mostly useful when passing and returning from functions.
Topic archived. No new replies allowed.