returning two ints from a function

I want to return two values from a function, I tried doing it like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

int function()
{
  return  1,2;
};

int main()
{

  int a = 0;
  int b = 0;

  a,b = function();
  std::cout << a << ' ' << b << std::endl;

  return 0;
}


but function only returns the second value(2) to the second variable(b), the result is just:
0 2


Is there any way to get two results from a function?

Thanks, Ellipse
You can't return them in that fashion. You could have them in a struct and return them like that. Or you can pass in blank values via reference and alter them that way.

Reference:
1
2
3
4
5
6
7
void changeThem(int *X, int *Y) {
 (*X) = 3;
 (*Y) = 6;
}

// Called like:
changeThem(&a, &b);
Thanks, it worked!

I've always been unsure about pointers, never really known what they are good for..

Thanks.
Pointers have 2 main functions.

1) They are used to point at memory addresses. This is useful because you can do as I have showed you to do. Pass variables by address (reference) and use a pointer to modify them.

2) Allocate memory dynamically. But this is also a moot point for other language developers because you have to manage your memory and de-allocate it manually too. This is the function that most ppl tend to avoid in C++ when learning it because it's "difficult"
Hm .. OK, Thanks!
Hmm, C++ template magic can do what you want...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <map>

using namespace std;

// Our template functor
template <typename T1, typename T2>
struct t_unpair
  {
  T1& a1;
  T2& a2;
  explicit t_unpair( T1& a1, T2& a2 ): a1(a1), a2(a2) { }
  t_unpair<T1,T2>& operator = (const pair<T1,T2>& p)
    {
    a1 = p.first;
    a2 = p.second;
    return *this;
    }
  };

// Our functor helper (creates it)
template <typename T1, typename T2>
t_unpair<T1,T2> unpair( T1& a1, T2& a2 )
  {
  return t_unpair<T1,T2>( a1, a2 );
  }

// Our function that returns a pair
pair<int,float> dosomething( char c )
  {
  return make_pair<int,float>( c*10, c*2.9 );
  }

// And how we test the pair.
int main()
  {
  int   a;
  float b;
  unpair( a, b ) = dosomething( 'A' );
  cout << a << ", " << b << endl;
  return 0;
  }


Heh heh heh...
"magic". You mean "torture". I hate working with Templates =\ Inheritance FTW
Topic archived. No new replies allowed.