chris
chris

Reputation: 137

Returning multiple values from a function in C

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.

Upvotes: 3

Views: 280

Answers (4)

P.P
P.P

Reputation: 121387

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;
.....

Upvotes: 4

Punit Vara
Punit Vara

Reputation: 4194

return x; return y;

you have used return x. This function will return value to the calling function Now it will not come back and again return execute return y.Whenever you use return statement, you use keep in mind what actually return statement do ?

The return statement terminates the execution of a function and returns control to the calling function

So possibly you could refer this SO Q&A for solution of your problem. Other answers are also quite nice.

Upvotes: 0

Déjà vu
Déjà vu

Reputation: 28830

Use pointers for x and y. Instead of returning values, the function is setting the values:

void getPositionsH(int r, int ans, int size, int *x, int *y) {
    *x = ans == 9 ? 0 : rand() % size;
    *y = rand() % 10;
}

to be called

int x,y;
getPositionsH(r, ans, size, &x, &y);
// use x and y as you wish...
int total = x + 7 * y;

getPositionsH is given two pointers (the address) to x and y. Using *x = sets the value of x (declared before the function call).


Note

The

    *x = ans == 9 ? 0 : rand() % size;

statement is equivalent to

    if (ans == 9) *x = 0;
    else *x = rand() % size;

Upvotes: 0

shakhawat
shakhawat

Reputation: 2727

you can't return two values this way.

int getPositionsH(int r, int ans, int size)

being declared as int return value will return only a single int

 return x;
 return y;

After returning x, program execution will return from the function, thus return y will remain unreachable.

Upvotes: 1

Related Questions