References (C++ only)
A reference is an alias or an alternative name for an object. All operations applied to a reference act on the object to which the reference refers. The address of a reference is the address of the aliased object.
A reference type is defined by placing the reference modifier &
after
the type specifier. You must initialize all references except function
parameters when they are defined. Once defined, a reference cannot
be reassigned because it is an alias to its target. What
happens when you try to reassign a reference turns out to be the assignment
of a new value to the target.
Because arguments of a function are passed by value, a function call does not modify the actual values of the arguments. If a function needs to modify the actual value of an argument or needs to return more than one value, the argument must be passed by reference (as opposed to being passed by value). Passing arguments by reference can be done using either references or pointers. Unlike C, C++ does not force you to use pointers if you want to pass arguments by reference. The syntax of using a reference is somewhat simpler than that of using a pointer. Passing an object by reference enables the function to change the object being referred to without creating a copy of the object within the scope of the function. Only the address of the actual original object is put on the stack, not the entire object.
int f(int&);
int main()
{
extern int i;
f(i);
}
You cannot tell from the function call f(i)
that
the argument is being passed by reference.
References to NULL
are not allowed.