# Function Returning Structures

• 03-26-2007
pritin
Function Returning Structures
I just want to know, how to use the function "sum" effectively, returned in the following code.

distance is a structure.

Code:

```distance &sum(distance L1, distanceL2); distance L3; // global structure distance &sum(distance L1,distance L2) { L3.feet=L1.feet+L2.feet+(L1.inches+L2.inches)/12; L3.inches=(L1.inches+L2.inches)%12; return L3; }```
• 03-28-2007
dwks
Well . . . sum() takes two distance structures, adds their contents and stores the result in the global variable L3, also returning a reference to L3. You could use it like so:
Code:

```distance one = {1, 9}, two = {2, 11}; distance both = sum(one, two);```
In my opinion it's not written very well. First of all, L1, L2, and L3 are very bad variable names. They could be anything. "result", "one" and "two" might be better. Secondly, using a global variable for just that is extremely wasteful. And why return a reference to the variable? It's already global . . . .
• 04-01-2007
pritin
#1 : SUPPOSE sum() returned a value, is it right to do

Quote:

cout << sum(L1,L2).feet;
-------------

#2 How to print values of L3 in the original case, where sum() returns a reference to L3 case?
• 04-02-2007
dwks
Quote:

Originally Posted by pritin
#1 : SUPPOSE sum() returned a value, is it right to do
Code:

` cout << sum(L1,L2).feet;`

You mean, will that work? Sure. This would work too:
Code:

```sum(L1, L2); cout << L3.feet;```
Quote:

#2 How to print values of L3 in the original case, where sum() returns a reference to L3 case?
You mean, how would you print the previous value of L3 after sum() has modified it? You can't. That's why I don't like using global variables. :)

You'd have to save the value first:
Code:

```distance prev = L3; sum(L1, L2); // L3 is the new // prev is the old L3```