[try Beta version]
Not logged in

 
 
How to return 2 variables ?

Jul 5, 2012 at 7:03pm
Hi,

my question is how to return 2 variables, one integer and one double, from a function ?

(pseudocode) i have a function :

1
2
3
4
5
6
7
8
9
int fun(){
 int x;
 double y; 

 //computations
 //...

 return x, y; 
}


Any help please ?

Thanks !
Jul 5, 2012 at 7:07pm
Something like this?
1
2
3
4
5
struct COMBO
{
     int x;
     double y;
};

And make the return type for the function the type for your object.
Jul 5, 2012 at 7:09pm
yes, right probably another solution could be to make one of those variables global.
Jul 5, 2012 at 7:10pm
1
2
3
4
5
6
7
8
9
pair<int, double> fun(){
 int x;
 double y; 

 //computations
 //...

 return make_pair(x, y); 
}
Last edited on Jul 5, 2012 at 7:10pm
Jul 5, 2012 at 7:16pm
@Cubbi

how to call the function fun() from main() ?

i mean for example when we have:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int fun(){
 int x; 

 //computations
 //...

 return x; 
}

int main(void){
  int y;
  y = fun(); // here i call function fun() 
  return 0;
}


when we have

1
2
3
4
5
6
7
8
9
pair<int, double> fun(){
 int x;
 double y; 

 //computations
 //...

 return make_pair(x, y); 
}


how to call this function from main() ?
Jul 5, 2012 at 7:29pm
In this case,
1
2
  int y;
  y = fun().first;

could also be
1
2
3
4
5
int x;
double y;
pair<int, double> p = fun();
x = p.first;
y = p.second;

or
1
2
3
int x;
double y;
tie(x, y) = fun();
Topic archived. No new replies allowed.