Please note that a
reference can’t be made to refer to another variable and this is the reason why it must be
initialized.
If you make any change to a reference, then that change is actually applied to the variable
to which the reference refers. As a result, all references to either name have the same effect.
For example,
v+ = 1;
will add 1 to ‘u’, the variable referred to by ‘b’.
Also note that each definition of a reference
must be preceded by the address-of operator—that is, & (ampersand).
For example,
#include
void main( )
{
int a = 100;
int &b = a;
printf(”\n a= %d b= %d“ , a, b);
b = 200;
printf(”\n a= %d b= %d“ , a, b);
a = 300
printf(”\n a= %d b= %d“ , a, b);
}
OUTPUT (after running):
a= 100 b = 100
a= 200 b = 200
a= 300 b = 300
Please note here that ‘b’ is called as a reference to ‘a’ and note that the ‘a’ variable and its
reference are so closely interlinked that if one changes, the other will automatically change.
Do'stlaringiz bilan baham: |