Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning multiple values from a function in C

Tags:

c

function

int getPositionsH(int r, int ans, int size){
    int x=0;
    int y=0;
        if (ans==9){
            x =0;
        } else
            x=(rand()%size);

        y=(rand()%10);  
    return x;
    return y;
}

Basically this is a function in c that is supposed to return 2 randomly generated positions x and y. However while debugging I noticed that x and y are still empty after this is executed. No idea why because I wrote return and everything. Any ideas why? Any help is appreciated.

like image 928
chris Avatar asked Dec 05 '25 15:12

chris


1 Answers

A function can return only one value in C. As it is, the function returns only x and the statement return y; has no effect -- it's unreachable code.

If you want to return multiple values, you can either pass pointers and return the values in their content or make a struct to and return values.

typedef struct position {
   int x;
   int y;
}pos_type;

pos_type getPositionsH(int r, int ans, int size){
    pos_type p;
    int x=0;
    int y=0;
        if (ans==9){
            x =0;
        } else
            x=(rand()%size);

        y=(rand()%10);  

    p.x = x;
    p.y = y;
    reutrn p;
 }

and in the caller:

pos_type t = getPositionsH(...);

int x = t.x;
int y = t.y;
.....
like image 82
P.P Avatar answered Dec 08 '25 08:12

P.P



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!