Difference between void my_func(int a) and void my_func(int& a)

Hi, I have been struggling to understand the purpose of references.
It seems that a reference is just a mixture of a pointer and an actual object.
So the question is, in which scenario and why in a function you would prefer to take as a parameter:

  • a reference -for example the function signature would look like void my_func(int& a)

  • an actual object - function signature would look like void my_func(int a)

“First, when passing a large struct or class to a function, pass by value will make a copy of the argument into the function parameter. In many cases, this is a needless performance hit, as the original argument would have sufficed. Second, when passing arguments by value, the only way to return a value back to the caller is via the function’s return value. While this is often suitable, there are cases where it would be more clear and efficient to have the function modify the argument passed in. Pass by reference solves both of these issues.”

So 1) it’s for performance. 2) it allows you to change the input values without relying on the return of the function.

I think this was used in an earlier lecture, hence us using #define OUT.

1 Like

Privacy & Terms