Returning a Reference in C++

Sasuke12

Beta member
Messages
5
I don't understand the second line of this code.

int& max(int& m, int& n)
{return ( m > n ? m : n )
}

int main()
{ int m = 44, n = 22;
cout<< m << ", " << n<< ", " << max(m,n)<< endl;
max(m,n)= 55;
cout<< m << ", " << n<< ", " << max(m,n)<< endl;
}

Also, what is the point to return the value with references?

Thanks in advance,
Sasuke12
 
Yeah, I read through the cplusplus web site. Really haven't seen something as strange as the second line. I don't understand (m>n ? m:n), simply what does it mean? Or can some one tell me what category does that belong to, so I can check it up myself.

And I assume that I have to use reference because they are using variables in a separate function, correct me please?
 
Okay, I might be wrong, but I believe the int& max function is being given two variables to use, and the function returns the larger variable with a conditional statement. If m > n is true, the code returns m, the variable before the colon. If m > n is false, the code returns n, because that means n > m. You can read the statement like so:

expression ? if true do this : if not true do this

Because the command happens to be return, it will return the selected variable. As for references, normally when you pass data from function to function, you don't pass the actual variable, but a copy. When you pass by reference, you pass the memory address of the original variable, rather than a copy, so you actually work with the original variable itself. This allows a function to make direct changes to variables in another function, and to return values of more than one variable at a time.

If you would like more information, go to http://www.cplusplus.com/doc/tutorial/. Conditional statements are located under "Operators," and references are locted under "Functions (II)"
 
C-- said:
Okay, I might be wrong, but I believe the int& max function is being given two variables to use, and the function returns the larger variable with a conditional statement. If M > n is true, the code returns m, the variable before the colon. If m > N is false, the code returns n, because that means n > m. You can read the statement like so:

expression ? if true do this : if not true do this

Because the command happens to be return, it will return the selected variable. As for references, normally when you pass data from function to function, you don't pass the actual variable, but a copy. When you pass by reference, you pass the memory address of the original variable, rather than a copy, so you actually work with the original variable itself. This allows a function to make direct changes to variables in another function, and to return values of more than one variable at a time.

If you would like more information, go to http://www.cplusplus.com/doc/tutorial/. Conditional statements are located under "Operators," and references are locted under "Functions (II)"


I would have to agree.
 
Back
Top Bottom