1. Home
  2. Computing & Technology
  3. C / C++ / C#
photo of David Bolton
David's C / C++ / C# Blog

By David Bolton, About.com Guide to C / C++ / C#

Know the difference between a Reference and a Pointer in C++?

Thursday August 10, 2006

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

Leave a Comment

Line and paragraph breaks are automatic. Some HTML allowed: <a href="" title="">, <b>, <i>, <strike>

Explore C / C++ / C#
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#

©2009 About.com, a part of The New York Times Company.

All rights reserved.