Lorem ipsum dolor sit amet, consectetur adipiscing elit. Test link
Posts

4.5 Reference

1 min read
Image result for References are another variable type of C+

References are another variable type of C++ that act as an alias or short name to another variable. A reference variable acts just like the original variable it is referencing. References are declared by using an ampersand (&) between the reference type and the variable name.

Declaration
int distance = 5;
// normal integer
int &ref = distance;
// reference to distance
The ampersand in this context does not mean “address of”, it means “reference to”.

Use of reference
distance = 6;
// distance is now 6
ref = 7;
// distance is now 7

cout << distance; // prints 7
distance++;
cout << ref; // prints 8

Using the address-of operator on a reference returns the address of the value being referenced:
cout << &distance; // prints 0012FF7C
cout << &ref; // prints 0012FF7C

Const references
It is possible to declare a const reference. A const reference will not let you change the value it references: int distance = 5;
const int &ref = distance;

ref = 6; // illegal -- ref is const

                      4.6 Enumration and typedef          NEXT >>

You may like these posts

Post a Comment