How do I return multiple values from a function in C?

Tony Stark picture Tony Stark · Apr 12, 2010 · Viewed 277.4k times · Source

If I have a function that produces a result int and a result string, how do I return them both from a function?

As far as I can tell I can only return one thing, as determined by the type preceding the function name.

Answer

Travis Gockel picture Travis Gockel · Apr 12, 2010

I don't know what your string is, but I'm going to assume that it manages its own memory.

You have two solutions:

1: Return a struct which contains all the types you need.

struct Tuple {
    int a;
    string b;
};

struct Tuple getPair() {
    Tuple r = { 1, getString() };
    return r;
}

void foo() {
    struct Tuple t = getPair();
}

2: Use pointers to pass out values.

void getPair(int* a, string* b) {
    // Check that these are not pointing to NULL
    assert(a);
    assert(b);
    *a = 1;
    *b = getString();
}

void foo() {
    int a, b;
    getPair(&a, &b);
}

Which one you choose to use depends largely on personal preference as to whatever semantics you like more.