Know the difference between a Reference and a Pointer in C++?
A reference can be thought of as a special type of pointer with certain restrictions. Once a reference points to a variable it is stuck. It cannot be reassigned. Personally I've found references most useful for simplifying access to variables when passed in as parameters to a function. Although a reference can only be attached once, because it belongs to the function, it can be assigned each time the function is called.
function example(int & value) {
// do something
}
for (i=0;i< 10;i++)
{
example( fred[i]);
}
Also important is the fact that each element of fred is being passed by reference. This means that value (within the example() function) is directly accessing the array fred[] and not a copy of each element. With small size variables like ints this is less important but if fred was an array of a very large object, then passing by value would need to copy each element which is slow. So passing by reference is a lot more efficient. It's just like the pascal 'var' parameter.


Comments
No comments yet. Leave a Comment