Can a function return more than one value?

Hi,
Just a quick simple question:
Can you make a function return more than one value?
Thanks in advance!
In terms of the keyword return, no.

People typically deal with this by either:

1) Creating a single type containing all the infomation they're interested in and returning that (e.g. a struct)

2) Returning an instance of some aggregate container type, or other such set of data (e.g. a std::pair, or a tuple, or a vector of some type, etc.)

3) Passing the function references to variables, which the function will then alter. When the function is finished, the caller can then just examine those variables to see what the function did.

4) Probably a bunch of ways I've forgotten
Last edited on
Good question Jonas420,

I am inclined towards the first idea "Repeater" mentioned.
Just create a struct that has the values you want as it's member data.
1
2
3
4
5
6
struct sample {
	datatype x;
	datatype y;
		.
		.
}

Access the members, use them and once you are done, return the struct.
Last edited on
Yes. C++17 make the syntax simple thanks to structured bindings.

https://skebanga.github.io/structured-bindings/
Okey, you guys got me thinking about the struct thing, but in a different way, which you couldn't know because I did not specify my question enough.
Suppose I create a data struct on the very top of my program, so a general struct, with an array to it as wel, like this:

struct{
int reward;
double resptime;
}data[NTRIALS];

If now in my trial function I were to change the value of both reward and resptime, would they then keep there new values as the program leaves the trial function? Without having to return anything, so just a void function?
yes, but you need to isolate the struct definition so you can use it elsewhere...

1
2
3
4
5
6
struct record {
  int reward;
  double resptime;
};

record data[NTRIALS];


then you can play...

1
2
3
4
5
6
7
8
9
10
11
12
13
void updateRecord(record& theRecord)
{
  theRecord.reward = 1;
  theRecord.resptime = 5.5;
}

record blankRecord()
{
    record r; 
    r.reward = 0;
    r.resptime = 0.0;
    return r;
}

1
2
3
4
5
{
  updateRecord(data[0]);
  updateRecord(data[5]);
  data[3] = blankRecord();
}

Last edited on
Topic archived. No new replies allowed.