Pass By Value and By Reference


Two alternate functions specified are given,
each of which simply triples the variable count defined in main.




I'm not so sure how to explain the differences and comparison

between the two approaches.




Please help me out...



:)












a) function tripleByValue that passes a copy of count by value,

triples the copy and returns the new value





b) function tripleByReference that passes count by reference

via a reference parameter and triples the original value of count

through its alias (i.e., the reference parameter).
tripleByValue will create a copy of the count variable when it is called. It then does its calculations on the COPY, not the original one that was defined in main. A return value is needed in this case because the COPY is deleted after the function finishes.

tripleByReference will not copy the count variable...it uses it directly. This approach saves time, especially for large data sets like arrays etc.

Hope that helps.
thank you soooo much ^ ^
However, in the case that the function takes only an integer parameter, I believe (however I'm not 100% sure) that it's actually faster to pass it by value. Any comments on that guys?
(and girls :) )
I'm a beginner, but passing by reference should be faster because the computer does not need to make an extra copy of what is being passed.
AFAIK the difference between passing by value and by reference is significant only when passing larger objects (e.g. a class). Larger objects is better to pass by reference. In case of an int it doesn't matter.
+1 to what Danielsson said.

Passing by const reference is for when copying an object would be expensive.

ints, floats, and other small built-in types are better to be passed by value since copying is cheap. Passing an int by const reference will probably have worse performance.

Here's an article which gives more detail: http://cplusplus.com/forum/articles/20193/
Topic archived. No new replies allowed.