Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

returning multiple values from a function [duplicate]

Tags:

c

Can anyone tell me how to return multiple values from a function?
Please elaborate with some example?

like image 560
Shweta Avatar asked Sep 30 '10 09:09

Shweta


People also ask

Can you return multiple values from a function?

We can return more than one values from a function by using the method called “call by address”, or “call by reference”. In the invoker function, we will use two variables to store the results, and the function will take pointer type data.

What are the two ways of returning multiple values from function?

Below are the methods to return multiple values from a function in C: By using pointers. By using structures. By using Arrays.

Can you return multiple variables?

You cannot explicitly return two variables from a single function, but there are various ways you could concatenate the two variables in order to return them.


1 Answers

Your choices here are to either return a struct with elements of your liking, or make the function to handle the arguments with pointers.

/* method 1 */
struct Bar{
    int x;
    int y;
};

struct Bar funct();
struct Bar funct(){
    struct Bar result;
    result.x = 1;
    result.y = 2;
    return result;
}

/* method 2 */
void funct2(int *x, int *y);
void funct2(int *x, int *y){
    /* dereferencing and setting */
    *x  = 1;
    *y  = 2;
}

int main(int argc, char* argv[]) {
    struct Bar dunno = funct();
    int x,y;
    funct2(&x, &y);

    // dunno.x == x
    // dunno.y == y
    return 0;
}
like image 133
mike3996 Avatar answered Oct 19 '22 18:10

mike3996