Pointers and References

Started by
1 comment, last by Elfs1der 20 years, 7 months ago
I need a solid definition of what the difference is with: passed-by-value, and pass-by reference. I really don''t get it.
Advertisement
When you pass something by value, you create a copy of whatever you're passing on the function's stack. Ergo, the function can't change the value of the passed variable outside its own scope. Example:
void function (int x){   // this doesn't do a thing because x is a local copy.   x = 7;}int main(){    int x = 3;    function (x);    // x is still 3, not 7.}  

Now, when you pass by reference (or with a pointer), the situation is different. Here, you do NOT make a new copy of the data. Instead, the function receives the memory address of the variable, and thus it can change it at will.
void function (int& x) // pass by reference{    // this is the same variable x (same memory location) that's      // in the main() function.    x = 7;}int main(){    int x = 3;    function (x);    // x is now 7!} 

You should pass by reference whenever you want a function to modify some of its arguments, or if you don't want the overhead of making a copy of a big data structure. Remember, a reference to a struct is just a memory address, and is thus (usually) faster to copy and pass than the struct itself.

[edited by - twix on August 31, 2003 1:31:41 PM]
quote:Original post by Elfs1der
I need a solid definition of what the difference is with:
passed-by-value, and pass-by reference.

I really don''t get it.


When you pass-by-value you are doing just that -- you are passing the *value* of the variable you give the function and not the actual variable. If you did math to the variable in your function and want to keep the result, you have to return it in the return statement. Thats because you were only working with a copy of the value stored in your original variable.

When you pass-by-reference, the variable name you call it within your function *refers* to the real/original variable. Whatever you do to that variable in your function, happens to the original variable (back in main() or wherever you called your function from). It *is* the original variable only under a new name. There is no need to return anything from your function now since you already changed it directly in the function.

Passing a pointer isn''t too much different from passing by reference. But let''s make sure you understand this, so far.

This topic is closed to new replies.

Advertisement