Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Returning more than one value???

Status
Not open for further replies.

Matilde

Programmer
Nov 30, 2001
18
DK
How do you return more than one value in a function? i.e. if you calculate several results and you want to reurn them...


double equation(double a = 0, double b = 0, double c = 0)
{

double sol1 = 0;
double sol2 = 0;

sol1 = (-b+sqrt((b*b)-4*a*c)/2*a;
sol2 = (-b-sqrt((b*b)-4*a*c)/2*a;

Return ????;
}
 
Code:
double equation ( double a,
                  double b,
                  double c,
                  double &sol2 )
{
  double sol1 = (-b+sqrt((b*b)-4*a*c)/2*a;
  sol2 = (-b-sqrt((b*b)-4*a*c)/2*a;
  return sol1; } 

...
 
sol1 = equation ( a, b, c, sol2 );
Marcel
 
As far as I know you cannot explicitly return more then 1 variable back through a function at a time.. You can however pass a pointer back to the variable to the function. This would allow the function to manipulate any number of variables and have their values changed by the function.

Hope that helps,
Kevin
 
In other words, in order to "return" more than one value, (it's true more than one value cannot be returned) you must pass the additional variables by address.

( int &var1, int &var2, etc. )

in this way, a function can manipulate the variables directly, and not be limited by the single return value limitation.
 
Or like this :
Use a structure inside as well as outside your function.
 
additional remark (the way I learned it as good programming)

a function should always have ONE return value.

your formula (-b (+/-) sqrt(b*b-4ac)/2*a) also can give you back ONE value at a time (of course there are 2, ONE for +, ONE for MINUS)
So I think it would be better to pass an additional parameter like PLUSPART and MINUSPART and use the function
like this :

double equation(int WHICHPART,
double a = 0,
double b = 0,
double c = 0)
{
if (WHICHPART == PLUSPART)
return (-b+sqrt((b*b)-4*a*c)/2*a;
else
return (-b-sqrt((b*b)-4*a*c)/2*a;
}
and then call the function two times.

This makes your program much clearer and much more readable It sure works returning values by return and in addition throu the parameters but that's like your guests leaving the house one throu the door and the rest throu the window.

by the way : it has to be /(2*a) instead of /2*a but maybe
that's only a typing error in your poste.
and don't forget : the sqrt-part could be negative.

 
If you need to return more than 1 parameter. Instead of passing pointers for individual parameters to functions it may be better to pass a pointer to a structure.

If more info is required then let me know
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top