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.
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.
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.
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
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