| |
GeekInterview.com > Interview Questions > Programming > C
| Print | |
Question: Difference between reference and pointer?
Answer: what is difference between reference and pointer or pass by reference and pass by pointer? |
| July 07, 2008 01:05:06 |
#1 |
| rocky2583 |
CRM Expert Member Since: July 2008 Total Comments: 3 |
RE: Difference between reference and pointer? |
In C there is no concept of a reference variable. Only pointers exist. When you pass address of any variable to a function, it is termed as pass by reference. Coz the formal parameter in function is the pointer that stores this address.
In C++, reference variables exist. A reference variable does not get any memory of its own. It must be initailzed when it is declared and it acts as an alias or synonym for the variable which was used to initialze it.
There are two ways to pass the variable by reference in C++
1) Traditional pass by reference approach. someFunction (&a, &b);
void someFunction (int *x, int *y) { }
2) someFunction (a, b); void someFunction (int &x, int &y) { } In this case no memory is allocated to x & y. They act as alias for the memory locations to which a & b are referring. any changes made to the values of x & y will cause values of a & b in the calling function to change respectively.
Both approaches 1) and 2) are called pass by reference. But first approach uses pointers and second approach uses reference variables.
|
| |
Back To Question | |