inimene
inimene

Reputation: 1650

C - Returning 2 values in a function and trying to use them

So I have this function where I return 2 values:

return result, result2;

Now what I am trying to do is use these 2 values in my main function. I want to save it into a variable in main function like this :

variable = function(a,b);

But how do you specify here which value you want?

Upvotes: 5

Views: 322

Answers (6)

Daniele
Daniele

Reputation: 831

you could also use a struct containing two values and then return it.

another solution is also possible if you have two 32 bit values. Infact, you can store both of them in a 64 bit variable. Example:

uint32_t a = 10;
uint32_t b = 20;
//store both into c:
uint64_t c = (a << 32) + b;
//restore a and b:
a = c >> 32;
b = c & 0xFFFFFFFF;

Upvotes: 3

Emu
Emu

Reputation: 5905

You can use an array to return the values:

#include <stdio.h>

/* function to generate and return 2 numbers */
int * function( )
{
  static int  r[2];
  int i;

  r[0] = 10;
  r[1] = 20;

  return r;
}

/* main function to call above defined function */
int main ()
{
   /* a pointer to an int */
   int *p;
   int i;

   p = function();
   for ( i = 0; i < 2; i++ )
   {
       printf( "%d\n",*(p + i));
   }

   return 0;
}

Upvotes: 2

fede1024
fede1024

Reputation: 3098

No, you cannot do this in C, you can just return one value. The comma operator returns just the last value, so you are actually returning the second one.

You can pass data by reference, like

function(&a, &b);

void function(int *a, int* b){
    *a = 42;
    *b = 666;
}

You can also put them in a structure and return it or even a pointer to a dynamically allocated structure.

typedef struct int_pair {
    int a, b;
} int_pair;

int_pair function(){
    int_pair s;

    s.a = 42;
    s.b = 666;

    return s;
}

Upvotes: 13

doctorlove
doctorlove

Reputation: 19317

You can do this in python and matlab and possibly other languages but not C, or C++ or other languages.

In C++ you could return a pair.

In C you could pass in two pointers and send back the return values that way, or if they belong together make a struct with both values in and return that.

Upvotes: 4

arunb2w
arunb2w

Reputation: 1196

Instead of returning values from the function to main(). Try to pass them references to the calling function(i.e) their addresses to achieve this.

Upvotes: 2

Some programmer dude
Some programmer dude

Reputation: 409482

What you are doing with that return Statement is using the comma expression. What the comma expression does is to evaluate both sub-expressions, from left to right, but return the result of the right sub-expression, meaning the return statement returns the result of the right sub-expression as well.

In C you can not return multiple values with the return Statement. Only one or none.

Upvotes: 3

Related Questions