1

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.

3
  • 4
    How are you getting {1,2} from f? You can't return an array... Commented Oct 25, 2010 at 20:33
  • 1
    What return type does f() have? Commented Oct 25, 2010 at 20:37
  • 2
    What is the signature of f? Or at least, what is f's return type? Commented Oct 25, 2010 at 20:38

4 Answers 4

3

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.
Sign up to request clarification or add additional context in comments.

Comments

2

Use the std::array array wrapper instead:

std::array<int, 2> f(int, int);

std::array<int, 2> result = f(1, 2);

Comments

2

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

1

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

Liked the second part of using struct. Did not like the memcpy part.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.