Passing by reference in C++

Started by
6 comments, last by Guthur 15 years, 3 months ago
Just a quickie... Is there any (semantic) difference between the following methods of passing by reference:

void Foo(int* theNumber)
{
   // Stuff
}

void Bar()
{
  int myNumber = 0;
  Foo(&myNumber);
}


void Foo(int& theNumber)
{
   // Stuff
}

void Bar()
{
  int myNumber = 0;
  Foo(myNumber);
}

Advertisement
The contents of //stuff will be slightly different (ie you'll be doing (*theNumber) = x instead of theNumber = x, other then that there's no difference I don't think.
Quote:Original post by BosskIn Soviet Russia, you STFU WITH THOSE LAME JOKES!
There are two semantic differences. In the pointer case Null is an allowable value, in the reference case it isn't. They differ semantically since the pointer is an explicit reference(must dereference to get the value) where as the reference is an implicit reference(no dereference needed), as pointed out by grekster.
The only significant difference between the two is that the pointer can be checked for NULL while the reference will always have a value. If the parameter can be null (i.e. an output value you can or cannot be interested in, or a buffer than has not yet benn initialized) pointers are usually used.
Making the pointer const might bring it even closer to a reference.

Neither of them are NULL though :s
Innovation not reiterationIf at any point I look as if I know what I'm doing don't worry it was probably an accident.
Quote:Original post by m0nkfish
Is there any (semantic) difference between the following methods of passing by reference:


The main semantic difference between your two snippets is the first is passing by value and the second is passing by reference.

Passing by value and passing by reference have quite marked semantic differences, as any first-year textbook on computer science should tell you. At least it did back in my day, but that was long loooong ago. Maybe, since the invention of the PC, things like that just don't matter so much anymore.

What might confuse you is that before your first snippet's Foo function call, you are taking the address of a local variable. You then pass that address by value to Foo, which likely performs various operations on that address like dereferencing it. In your second snippet, you pass your local variable by reference and Foo likely performs various operations on it.

Ya know, the semantics of the two snippets are about as similar as dogs and rainbows.

Stephen M. Webb
Professional Free Software Developer

Thanks for clearing that one up for me :)
Quote:Original post by Bregma
...

Passing by value and passing by reference have quite marked semantic differences, ...


hhh so obvious yet so missed by us all, kudos :)
Innovation not reiterationIf at any point I look as if I know what I'm doing don't worry it was probably an accident.

This topic is closed to new replies.

Advertisement