What is the difference between returning by reference and returning by value, examples if possible?
Far greater efficiency is achieved in returning by reference. Memory is saved and
the program runs faster.
What is the difference between returning by reference and returning by value, examples if possible?
Far greater efficiency is achieved in returning by reference. Memory is saved and
the program runs faster.
reference is work like constant pointer ,so all advantages of return by pointer works.
I suppose returning by value would be this:
whereas returning by reference would be:Code:int func(); // prototype int x = func();
This saves memory and some processing (moving of values) because rather than computing a value in func() and then copying that value into x, as in the first example, the second example computes the value straight into n, so no copying is required. This is more significant if the function requires an input of the same type, eg, if it calculated the square or something. In that case we'd have to alter example one:Code:void func(int &x); //prototype int n; func(n);
More copying.Code:int func(int x);
Still, "far greater" depends on the context. What's important is that you understand the concept and know how to apply it. It does not have to be your #1 priority or anything (altho C/C++ tends to work this way naturally due to the syntax -- references and pointers are very common and almost impossible to not use).
Last edited by MK27; 05-28-2010 at 11:01 AM.
C programming resources:
GNU C Function and Macro Index -- glibc reference manual
The C Book -- nice online learner guide
Current ISO draft standard
CCAN -- new CPAN like open source library repository
3 (different) GNU debugger tutorials: #1 -- #2 -- #3
cpwiki -- our wiki on sourceforge
Same concept behind passing by reference and value, really.
I think MK27 raises a good point: what exactly do you mean by "returning by reference"? I would expect:
i.e., the return type of the function is a reference type. MK27's example, on the other hand, illustrates the use of a reference parameter as an in/out or out parameter. For what I expect, the choice between returning by value and returning by reference should not only be made on efficiency grounds. One must consider correctness, as it would be incorrect to return a reference to a local variable.Code:int& foo();
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)