C++(cplusplus)-references-pointers
Properties of References:
main() { int i , j ; int *ptr = &i; ptr = &j; }
Gives Error
2. ArithmeticOperations cannot be performed on a reference.
main()
{
int i;
int &ref = i ;
ref++ ;
cout << ref ;
cout << i ;
}
The output of this program would be such that value of reference would not be incremented.But value of i will be incremented.
3. References are always automatically de-referenced.For ex:
int i ;
int &ref = i ;
&ref returns address of i that is when we try to print the address of reference the address of referent gets printed.
4. Passing a variable to a function by reference is better than passing by value.
The change in the calling function gets reflected in the called function.Moreover passing by reference eliminates the copying of object parameters back and forth.Hence it saves memory usage.
void func(int &x)
{
x=x-10;
}
int main()
{
int p=20;
func(p);
}
When fuction func is called,following initialization takes place:
int & x= p;
So, x become an alias of p on execution of the statement: func(p);
Here x and p are aliases of the same memory location.

Recent comments
6 days 22 hours ago
2 weeks 4 days ago
4 weeks 6 hours ago
4 weeks 2 days ago
4 weeks 4 days ago
4 weeks 5 days ago
29 weeks 1 day ago
29 weeks 5 days ago
29 weeks 5 days ago
30 weeks 14 hours ago