eveo
eveo

Reputation: 2843

How do you pass multiple variables from functions to main in C?

How do I pass back a local variable from a function to main, if said function already has a return value? Sorry for the question, I'm trying to make it as objective as possible for everyone, not just my case.

Specifically: I have a function called subtotal. There are two counting variables. One of them I returned with a return. The other I need to make available for use by my main() function.

edit: To clarify:

function something() {
   float counter = 0.0;
   int someOtherVar = 0;

   // the work

   return someOtherVar;
}

What I want to do is pass the counter float to main.

Upvotes: 2

Views: 3343

Answers (2)

Mat
Mat

Reputation: 206841

Put all your return values in a struct, and return that.

#include <stdio.h>

struct myret {
    int total;
    int count;
};

struct myret foo(void)
{
    struct myret r;
    r.total = 42;
    r.count = 2;
    return r;
}

int main(void)
{
    struct myret r = foo();
    printf("%d %d\n", r.total, r.count);
    return 0;
}

Or use pointers for the "other" return values.

int foo(int *other)
{
   if (other)
     *other=42;
   return 1;
}

int main(void)
{
   int a = 0;
   int b = foo(&a);
   ...
}

You can also combine both by passing a pointer to a struct to your function, and have your function fill that in:

#include <stdio.h>

struct myret {
    int total;
    int count;
};

int foo(struct myret *r)
{
    if (r) {
        r->total = 42;
        r->count = 2;
    }
    return 0;
}

int main(void)
{
    struct myret r;
    int rc = foo(&r);
    if (rc == 0) {
        printf("%d %d\n", r.total, r.count);
    }
    return rc;
}

Upvotes: 11

David Heffernan
David Heffernan

Reputation: 613282

Pass a pointer to the extra return value as a parameter to the function.

int foo(int *anotherOutParam)
{
    *anotherOutParam = 1;
    return 2;
}

And to call it:

int ret1, ret2;
ret1 = foo(&ret2);
//do something with ret2

Oftentimes, @Mat's suggestion of packing all the return values into a struct is preferable.

Upvotes: 9

Related Questions