returning multiple variables from function

Hello,

I'm trying to return two integers from a function, but I can't get it to work. Actually I want to do this for two chars (returning two filenames) but I thought I should try it with integers first.

I'm sorry if it's a trivial mistake, but I can't see where I'm going wrong and I'd really appreciate some advice (I'm new to c++):

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
#include <iostream>
using namespace std;

// Declare function prototype as the address of two integers
void ReadInput(int& a, int& b);

int main()
{
	
	int a, b;
	
	// call function, passing the two variables
	ReadInput(a,b);

	cout << a << " " << b << endl;

	return 0;
}

// declare function, taking as input the address of the integers
void ReadInput(int& a, int& b)
{
	// assign values at the address of the variables.
	*a = 5; // error at this line
	*b = 4; // error at this line
}


Thanks for your help!
Since you are passing by reference (this is slightly different than passing by pointer), you don't use the *. The references are "already dereferenced" you could say.
Try this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;

void ReadInput(int *a, int *b);

int main()
{
	int a, b;
	
	ReadInput(&a,&b);

	cout << a << " " << b << endl;

	return 0;
}

void ReadInput(int *a, int *b)
{
	*a = 5; 
	*b = 4;
}


You give the function the "address" of a and b (that's what the & means).
Then the function uses the "Value" at this address.
Last edited on
Another way (less suited to this application) is to return a pointer to an array. Not useful here, but it may be better is other applications.
Topic archived. No new replies allowed.