References
A reference is a second kind of variable that holds the address of another variable. That is, the reference points to another variable. Unlike pointers, which can refer to a valid variable, an invalid memory location, or nullptr
, a reference must be initialized to point to a variable when declared.
One difference between references and pointers is that a reference cannot be updated; once it is declared, it always points to the same variable. This means that a reference can't be incremented to step through an array the same way that a pointer can.
A second difference is that references are implicitly dereferenced in use. Arithmetic and relational operators applied to references affect the pointed-to variable. If ir
is an int
reference, then the statement ir = ir – 10;
subtracts 10 from the referenced int
. Mathematical expressions involving references, therefore, have a very natural appearance. A developer can use references to efficiently point to a variable...