Returning Multiple Values

Oct 9, 2013 at 12:04am
I would like to return multiple values from one function to access in different functions. For example:

int function1(//what goes here?)
{
int a ;
a = 1 + 2 ;
int b ;
b = 3 + 4 ;

return (what goes here if i want to return the value of a and/or b to use in another function?) ;

void function2()
{
//now i want to use the value of a here to use in an equation, how do i do that?

//now i want to use the value of b here to use in an equation, how do i do that?
}

Any feedback is appreciated. Thank you!
Oct 9, 2013 at 12:23am
You can't return two primitives at once. There is a way around this but chances are you aren't ready for it yet.
Oct 9, 2013 at 2:29am
use a struct to store the values. Then return the struct and extract the values you need
Oct 9, 2013 at 3:26am
What Smac89 meant to say was:
Use std::pair, and if you need to return more than two values use std::tuple.
http://www.cplusplus.com/reference/utility/pair/
http://www.cplusplus.com/reference/tuple/tuple/
Oct 9, 2013 at 5:04am
If you have a small number of variables to return, sometimes its just as easy to pass the variables by reference, like this:
1
2
3
4
5
6
7
8
9
10
11
void function1(int &a, int &b) {
    a = 1+2;
    b = 3+4;
}

void function2(void) {
    int a, b;
    function1(a, b);

    std::cout << "A: " << a << "\tB: " << b << std::endl;
} 
Topic archived. No new replies allowed.