### Using a pass by reference

Hey, this weeks assignment asked us to do a pass by reference. If anyone can give me an example or explain how to do it I'd really appreciate it.
This is the code I have so far.
 ``12345678910111213141516171819202122232425262728293031323334353637383940414243`` ``````#include using namespace std; int Largestnumber(int); int LargestNumber(int TheNum) { int FactorCount = 0; for (int i=TheNum; i>=2; --i) { for (int j=2; j> Input; Result = LargestNumber(Input); cout << "The largest number before " << Input << " is " << Result << endl; return 0; }``````
Examples and a good explanation here:
http://www.cplusplus.com/doc/tutorial/functions2/
Last edited on
I honestly don't even know how I'd include it... that kind of just confused me.

EDIT : I don't know how I'd include it without redoing my entire code.
Last edited on
I had a slight misconception about it at first, but I understand it well now. I'll show the first way you learn to pass data with a function
 ``1234`` ``````void A_function(int x) { x = 12; }``````

In this function, when you pass a variable in, you aren't actually changing that variable, it's creating a copy of that variable, then when we use ` x = 12; ` we are setting the copy equal to 12. Sometimes you might want this, but other times you might not. So instead of passing by value, we have passing by reference.

 ``1234`` `````` void Another_function(int &x) { x = 12; }``````

The & in the parameter means we will be directly accessing the variable passed in since we will be throwing in the memory address.

Look at the functions applied

 ``12345678910111213141516171819`` `````` #include void A_function(int x) { x = 12; } void Another_function(int &x) { x = 12; } int main() { int a = 1; int b = 1; A_function(a); Another_function(b); std::cout << a << std::endl; std::cout << b << std::endl; }``````

Compile that in your IDE and notice that ` int a` did not change because it was passed by value, but `int b` did, since we directly accessed it by using passing by reference.
That seems to make more sense... I am starting to understand it now, but I don't exact understand the use. What exactly is even the point?
Consider if you needed to swap numbers many times, you dont want to write it over and over, so you would make a function:
 ``123456`` ``````void swap(int& x, int& y) { int temp = x; x = y; y = temp; }``````

It would only work if they are passed by reference.

`cin` is an object, and there can only be one. You can pass it through a function, but it must be by reference.

The main point is that when you pass by reference you are working with the actual variable, not a copy of it. As your code becomes more complicated, you are going to want to send the actual variable in a function.
Indeed, and in some cases you need to avoid using more memory. When you pass by reference you aren't creating another variable, and so you are putting less demand on your computer.
Topic archived. No new replies allowed.