C++ Reference Types Bob Walton, 7/16/96 int & x; is similar to int * x; except you use x and not * x to name the object, and & x and not x to name the address of the object. Its just syntax, and NOTHING ELSE. For example, given struct foo { int first_index; }; if you write: int count ( foo & x ) { return x.first_index ++; } ... count ( z ) ... the compiler produces the same object code as if you had written: int count ( foo * y ) { return y->first_index ++; } ... count ( & z ) ... The reference type indicator & can be used in a declaration ONLY just in front of the name of a variable, or just in front of the name of a function in declaring the return value of the function. The resulting variable or function is called a reference variable or a reference function. A reference variable holds not a value but the address of a value, and storing a value in the variable stores the address of the value instead of the value. Reading the variable value uses this address to locate the value. Reference variables cannot be assigned to. They can be initialized (given initial values) as in: int y; int & x = y; which makes x and y have the same address. Reference variables may be used as arguments and receive values by argument passing. Use of & in front of a function name as in int & counter ( foo & x ); treats the function name as if it were the name of a variable in which the value of the function were returned. The function therefore appears to return a value (e.g. an int in the above example), but in fact returns an address. A return statement executed by the function designates the value whose address is returned. Given the above struct foo, one could write: int & counter ( foo & x ) { return x.first_index; } foo y; ... ... ++ counter ( y ) ... One must be careful to avoid code such as: int & counter ( void ) { int bar; return * & bar; } that allocates an int variable bar to the stack and then returns its address. The problem is that the variable bar is freed when the counter function returns, so the address is left pointing at `thin-air' by the time the caller of this function gets it.