• C

how to return multiple values from a function

how to return multiple values from a function
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

You can return a struct
evilrixSenior Software Engineer (Avast)Commented:
A function can only return one entity. The simplest way handle multiple values to have in/out parameters. In the example below I pass 2 int types to a function by pointer, they are modified in that function and the changes are visible outside of the function.
#include <stdio.h>
void foo(int * p1, int * p2)
	*p1 = 9;
	*p2 = 3;
int main(int argc, char* argv[])
	int i1, i2;
	foo(&i1, &i2);
	printf("%d %d", i1, i2);

Open in new window

There are two principal ways of doing this :

1) put all values you want to return in a struct :

        typedef struct ReturnType {
            int i;
            double d;
        } ReturnType;

    and then define your function like this :

        ReturnType fun() {
            ReturnType rt;
            rt.i = 5;
            rt.d = 3.0;
            return rt;

    and call the function like this :

        ReturnType rt = fun();
        printf("%d %f\n", rt.i, rt.d);

    the printf will show :

        5 3.0

2) pass the return values via the function parameters :

        void fun(int *i, double *d) {
            *i = 5;
            *d = 3.0;

    and call the function like this :

        int i = 0;
        double d = 0;
        fun(&i, &d);                 /* <--- pass the addresses of i and d */
        printf("%d %f\n", i, d);

    the printf will again show :

        5 3.0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
you can also set global variables, or some cases encode multiple values into a single value
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.