Difference between Call by Value and Call by Reference...

Hi
This is a really noobish question I'm sure.
I've read my books coutless times, But I've really been having trouble with this concept. And I'm falling behind in doing so. My lecturer assumes a good base knowledge of C++ which makes me a little hesitant to ask.

Could someone explain to me - as simply as possible - the differences between call by value and call by reference parameters? And what are the benefits of using reference as opposed to value?

I have an idea, but I need to getthis clear in my head. Things are getting quite complex with us moving onto pointers and containers so I really need to understand this.

Thanks
-greg
Call by value:

1
2
3
4
5
6
7
  void foo( int x ) {
      cout << x << endl;
      x = 4;
  }

  int someVar = 5;
  foo( someVar );


The value 5 is pushed onto the stack and foo is called. Inside foo(), 5 is popped off the stack and output. x = 4 modifies the stack copy, which is then thrown away when the function returns.

1
2
3
4
5
6
7
  void foo( int& x ) {
      cout << x << endl;
      x = 4;
  }

  int someVar = 5;
  foo( someVar );


The address of someVar is pushed onto the stack and foo is called. Inside foo, the address is popped off the stack and the integer stored at that address is output. x = 4 modifies the memory referred to by the address, which means that when foo() returns, someVar now has the value 4.

Contrast the above code to

1
2
3
4
5
6
7
  void foo( int* x ) {
      cout << *x << endl;
      *x = 4;
  }

  int someVar = 5;
  foo( &someVar );


This code does the exact same thing as my reference example, it's just the syntax is a bit different: note the &someVar where foo is called, and note the *x in foo() to refer to the integer value.

Yes, a 'reference' is really just a veiled pointer. It is just easier to read and use. (And it can be optimized in ways a straight pointer can't.)
Hi!
I have question which connects to this problem I think. In the tutorial on this page there is a very clear description about the following: "type* variable" means that variable is a pointer and it points to the type written in the declaration, but there is nothing about a declaration like "type& variable"(i.e. void foo(int& x) written above). So finally my question is: how can I read this or what does it mean?
Thanks
Boti
Read it as "the data address of an int called x" or "the data address of int x". Basically, it's what the pointer points to.
Thanks for your reply.
One more question: Am I right if I say that
int* x
is a correct declaration, while the syntax:
int& x
is valid only as a function or constructor parameter?
Thanks
Boti
Last edited on
nNo you can have a reference to declare variables. Most i've seen prefer to use pointers though.
However reference variables must be initialized at the time of instantiation.

 
int& x;


is not legal because x is not initialized, but

1
2
int y;
int& x = y;


is legal.

Topic archived. No new replies allowed.