C++:
Reference Variable:
Reference is an alias created for the variable.
Anallogy:Nickname
Important example:
int a=10;
int &b=a;
cout<<"value a="<<a;
cout<<"value b="<<b;
O/P:
Value a=10
Value b=10
& is a reference operator.syntax int &b=a; creatres another name b for the variable a. i.e we can say b is a reference to a.
If we manipulate the value of b e.g b=10 then the value of a gets changed.
int a=10;
int &b=a;
b=20;
cout<<"valu a"<<a;
cout<<"valu b"<<b;
o/p:
Value a=20
Value b=20
WHILE USING REFERENCE WE SHOULD KNOW……..
Reference have to be initialized
No memory is allocated to reference
Difference between pointer and reference
Pointer is flexible collaction
Reference is a rgid collection
Int *p=&I;
Int k;
P=&k;
A pointer has to be de-referenced before you can access the value at the addres contained in it. A reference is moreover a direct connection as it’s just another name for the same memory location.
We can have an arry of pointers whereas we can not have an aray of reference.
Const keyword
Constants should be initialized
Int i=10;
Const int*p=&I;
P=&k(correct) (*p)++ incorrect
P++(correct) *p=20 incorrect
Here,the pointer itself is not a constant and neither is the integer that it is pointing tp, a constant.we can change the address in the pointer by assigning some other address to it.but we cannot modify the contgents of the variable that it is pointing to,through that pointer.
Note:See some other cases like
1.pointer to a constant integer
2.contant pointer to an integer
3.constant pointer to a constant integer




No comments:
Post a Comment