1. Home
  2. Computing & Technology
  3. C / C++ / C#
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
November 14, 2009 at 2:56 pm
(1) IntGk says:

It is true that the in this code passing reference of fred[i] is faster then passing values. But what is important is the difference between passing by value and passing by reference.
if you do not want the values of fred to be changed inside exapmle() you are bound to pass them by values. there you can not use reference or pointer though it makes the programm faster.beware.

November 17, 2009 at 5:39 pm
(2) hakayashii says:

If you don’t want to change the value inside the function you can use const refernces and pointers. Example:
int example( const& LargeObject value ){…}.

Now you can be sure that value wouldn’t change and the performance is the same as whitout const.

November 23, 2009 at 5:33 pm
(3) hakayashii says:

I have to correct my self, it should be ‘const LargeObject&’

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

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

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

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

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

All rights reserved.