Return Multiple Values From Function..

Basically I want two returns from this function to the caller.
Scenario is: The functions takes two inputs and returns addition of those 2 numbers and subtraction.

I have come up with a skeleton which I feel it making somewhat sense:

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
#include <iostream>
#include <string>

using namespace std;

int add_sub(int &val, int &val2)
{
     // Here I want to take the 2 values and add, as well as subtract.
    // and then return it
 
}


int main()
{
	int value1;
	int value2;

	cout <<"Enter first number: ";
	cin >> value1;

	cout <<"Enter second number: ";
	cin >> value2;


	cin.ignore();
	cin.get();

	return 0;
}
Last edited on
You can define a structure with two members and return it to the caller. The C++ has already such template structure as std::pair. So you can define your function as


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
#include <iostream>
#include <utility>

using namespace std;

pair<int, int> add_sub( int val, int val2 )
{
	return ( make_pair( val + val2, val - val2 ) );
}


int main()
{
	int value1;
	int value2;

	cout <<"Enter first number: ";
	cin >> value1;

	cout <<"Enter second number: ";
	cin >> value2;


	std::pair<int, int> p =  add_sub( value1, value2 );

	cout << "sum = " << p.first << ", difference = " << p.second << endl;

	cin.ignore();
	cin.get();

	return 0;
} 




Hey, Thanks for the input but how would I do this with a pointer..

4. Write a function that takes two input arguments and provides two separate results to the caller, one
that is the result of multiplying the two arguments, the other the result of adding them. Since you can
directly return only one value from a function, you'll need the second value to be returned through a
pointer or reference parameter.

This is what the scenario asks..
void add_sub( int *sum, int *sub, int val, int val2 );
Thanks, Have managed to do it now:

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
#include <iostream>
#include <string>

using namespace std;

void add_sub(int *sub, int *add, int val, int val2)
{
	*add = val + val2;
	*sub = val - val2; 
}


int main()
{
	int value1;
	int value2;

	cout <<"Enter first number: ";
	cin >> value1;

	cout <<"Enter second number: ";
	cin >> value2;

	add_sub(&value1, &value2, value1, value2);
	cout <<"The sum is: " << value2 << endl;
	cout <<"The subtracted answer: " << value1;

	cin.ignore();
	cin.get();

	return 0;
}


Thanks, Again
Topic archived. No new replies allowed.