Say I get {1,2} from function f(a,b) (it doesnt matter what f is/does), and I want to store it into int s[2]. How would I do it? It seems that I can't just do int s[2] = f(a,b), and I can't separate the output of f, since there is no variable to get the values from. f(a,b)[0] does not work.
4 Answers
It all depends on what exactly f returns. You can't simply return {1, 2};, so it must be returning something else. Is it a decayed pointer to an array? An std::vector?
If it's a pointer, get the pointer returned and then assign the values.
int* p = f(a, b);
s[0] = p[0];
s[1] = p[1];
If s was bigger than two elements, then it would be better to use std::copy from <algorithm>:
int* p = f(a, b);
std::copy(p, p + 2, s); // where 2 is the size of the array.
Comments
To return two things from a function, I prefer std::pair:
#include <utility>
std::pair<int, int> f()
{
return std::make_pair(1, 2);
}
int main()
{
std::pair<int, int> p = f();
int s[2] = {p.first, p.second};
}
If the array already exists, you can make assignment even easier via boost::tie:
boost::tie(s[0], s[1]) = f();
Comments
You could copy it, as in memcpy( dest, f(1,2), size ).
Or you could just return a struct. It's an old trick to wrap an array inside a struct to easily copy it via operator=(). E.g.:
struct Foo { int a, b };
Foo f(int, int);
int main()
{
Foo myF = f(1,2);
}
The struct wrapping becomes useful later on, when your code evolves and you decide to return a third value. Being a struct means you can make it a backward compatible change and avoid changing as much other code...
1 Comment
struct. Did not like the memcpy part.
{1,2}fromf? You can't return an array...f()have?f? Or at least, what isf's return type?