how to return multiple values from a function

how to return multiple values from a function
Who is Participating?
Infinity08Connect With a Mentor Commented:
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
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

you can also set global variables, or some cases encode multiple values into a single value
All Courses

From novice to tech pro — start learning today.