-1
int addmult(int ii, int jj){
  int kk, ll;
  kk = ii + jj;
  ll = ii * jj;
  return (kk, ll);
}
void main(void){
  int i=3, j=4, k, l;
  k = addmult(i, j);
  l = addmult(i, j);
  printf("%d, %d\n", k, l);
}

The code prints "12, 12".

I thought that it wasn't possible to return two variables from a function. How does the compiler know to print ll instead of kk? I know that in the function ii=3 and jj=4, k=7 and l=12, but then it goes on to return two variables. Could someone please elaborate on why it ends up printing:

12, 12
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
Alex
  • 13
  • 3

1 Answers1

1

The function isn't returning two values, you have stumbled upon the Comma operator.

/**
 *  Assigns value of b into i.
 *  Results: a=1, b=2, c=3, i=2
 */
int a=1, b=2, c=3;              
int i = (a, b);           

The function is just returning the value of ll, you want to use reference parameters to return the two values.

void addmult(int ii, int jj, int* kk,int* ll){
  *kk = ii + jj;
  *ll = ii * jj;
}
void main(void){
  int i=3, j=4, k, l;
  addmult(i, j, &k, &l);
  printf("%d, %d\n", k, l);
}
unDeadHerbs
  • 1,306
  • 1
  • 11
  • 19