1

I was reading a book on C++ and there was an example where they passed by reference a constant to a function.

int square(const int& n)
 ...

I can't see the point of this? Why not just pass it normally by value if you are not going to be making any changes to the variable. Isn't the whole point of passing by reference so you can change the value of a variable.

David G
  • 94,763
  • 41
  • 167
  • 253
chasep255
  • 11,745
  • 8
  • 58
  • 115
  • Pass by value makes a copy, not that it matters with an int. – chris Oct 13 '13 at 18:59
  • An object may be expensive to copy (think of a large vector for instance). Passing by reference (const or not) saves the cost of making a copy. – john Oct 13 '13 at 19:01
  • `const` references are used to avoid , unnecessary copying of objects. However, I think, for primitive data types, it doesn't aid to any sort of performance. – P0W Oct 13 '13 at 19:07

3 Answers3

1

It probably makes no real difference for an int. But for a larger data type then passing const reference is a performance optimisation. So many coders just use const reference instead of by value out of habit.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
0

For complex types, passing by value is much more expensive than passing by reference because a copy of the value has to be made to pass to the function. Consider passing a large vector to a function that computes the median value. Do you really want to allocate a new vector, copy all the values in, perform the average over the new vector, and then free the memory you allocated? Passing by reference saves the allocate/copy/free cycle.

For int, it doesn't matter. In fact, on most platforms passing by value will be cheaper.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
  • That makes sense. I am used to Java where objects are automatically passed by reference. So if I had a vector, and I passed it by value to a function, and the function made some changes to it, those changes would not be reflected in the original vector unless I pass by reference. – chasep255 Oct 13 '13 at 19:35
  • @chase In Java, parameters are always passed by value. – David Heffernan Oct 13 '13 at 20:08
0

If you pass it by reference, you only pass the pointer, which is a "smaller" thing to pass. Also, the object is not copied in your function, so you use less memory in total.

dorien
  • 5,265
  • 10
  • 57
  • 116