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 Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Returning "types" from functions

Status
Not open for further replies.

pghsteelers

Technical User
Apr 21, 2006
121
US
Using C++ stating your prototype such as:

<type> functionname(type arg1, type arg2....)


My question is, if you are passing two variables one of type float and one of type int, and you want to pass them both back, what do you specify as the "return type"? Or can you not do that?

float myfunction(float n, int t)
{
...
...
...
return n, t
}

is this possible?

what about one like

int myfunction(char a, int n)

Basically, can you return multiple type variables from a function? I know you can pass multiple types.
 
pass the values by reference.

for example

Code:
#include <stdio.h>
 
void swapnum(int [b]&[/b]i, int [b]&[/b]j) {
  int temp = i;
  i = j;
  j = temp;
}
 
int main(void) {
  int a = 10;
  int b = 20;
 
  swapnum(a, b);
  printf("A is %d and B is %d\n", a, b);
  return 0;
}

(see msdn for full documentation on passing by reference and by value)

If somethings hard to do, its not worth doing - Homer Simpson
 
What ADoozer suggested is the best way of returning multiple values. Another solution is to create a class or struct that contains both variables, then return the struct.

Keep in mind that if you pass the values in by reference (or alternatively by pointer) that means that the original values may be changed. If you don't want the original values to be changed, but you want two or more new values returned, make the original ones const (just to make sure they don't get changed) and either pass a class/struct back, or pass the new values by reference:
Code:
void AddTen( const int&  iOld,
           const float&  fOld,
                   int&  iNew,
                 float&  fNew )
{
   iNew = iOld + 10;
   fNew = fOld + 10;
}

int main()
{
   int i1   = 3;
   int i2   = 0;
   float f1 = 3.14f;
   float f2 = 0.0f;

   AddTen( i1, f1, i2, f2 );

   cout << "Old num\tNew num" << endl
        << i1 << "\t" << i2 << endl
        << f1 << "\t" << f2 << endl;

   return 0;
}
 
If it is just two values, you could use an STL pair.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top