0

Okay, so here is the code.

#include <stdio.h>
int addmult (int,int);
int main (void)
{
    int i=3,j=4,k,l;
    k = addmult(i,j);
    l = addmult(i,j);
    printf("%d %d\n",k,l);
    return 0;
}

int addmult ( int ii, int jj )
{
    int kk,ll;
    kk = ii + jj;
    ll = ii*jj;
    return(kk,ll);
}

How is it that a function is returning two things simultaneously in C?

Edit: This code is perfectly working. I wish to know, why is it working?

user3797829
  • 383
  • 3
  • 15

1 Answers1

2

Are you asking what the line

return(kk,ll);

does or how you might return multiple values from a function?

To answer the first, this code is functionally equivalent to:

int ret = (kk,ll);
return ret;

Which might make it a little clearer. This is an instance of the comma operator, which evaluates to its second operand, so the code is in fact also functionally equivalent to:

return ll;

The kk value is never used.

To address the second possible interpretation of your question: use a struct, such as:

struct product_and_sum
{
  int product;
  int sum;
};

Change the function to return a struct product_and_sum and return a suitably initialised struct value.

pmdj
  • 22,018
  • 3
  • 52
  • 103
  • I got this. :) And I had one more doubt. If a function returns a value, then is it necessary to collect its value when it returns? – user3797829 Jul 12 '14 at 12:29
  • @user3797829 No that is optional for an example you don't collect returned value by `printf` function! ...additionally learn difference between `ret = (kk,ll);` and `ret = kk, ll;` – Grijesh Chauhan Jul 12 '14 at 12:31
  • 1
    Well, what is the difference if you can brief me a bit here? And also, not collecting the value is good enough for a user defined function as well, right? – user3797829 Jul 12 '14 at 12:32
  • @user3797829: It's not necessary e.g. you have instruction like `foo();`. However if you want to explicitely say that result is discarded, then you might provide void cast, e.g. `(void) foo();`. It does not have any effect on compiler, only for some static analysis tools like `splint` IIRC. – Grzegorz Szpetkowski Jul 12 '14 at 12:35
  • I am trying to know, is collecting the value of a function that will return a value, for example: `int foo( int a )` necessary or we can skip it as well? – user3797829 Jul 12 '14 at 12:37
  • 1
    @user3797829: lots and lots of functions return values. `sprintf`, for example, returns "the number of characters written to the output string". The question is: what would you *use* the return value for? For `sprintf`, you can use the return value or ignore it. Not using the return value of `sqrt` would be weird. – Jongware Jul 12 '14 at 12:46