0

I am trying to get some understanding about how pass by value & return are happening in C functions. I cam across a piece of code as follows:

#include <stdio.h>

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

int main()
{
 int i=4, j=5, k, l;
 k = fun(i, j);
 l = fun(i, j);
 printf("%d %d\n", k, l);
 return 0;
}

Now apparently I am not getting any errors when I am trying to return 2 values through fun().

Also, the value that is returned by fun() is ll i.e 20 (=4*5) and not kk. Further, If I rewrite the return statement as :

return (ll,kk);

the value returned is that of kk ie. 9 (=4+5).

Query: Why this is so?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
neo
  • 67
  • 4

3 Answers3

2

In your code, in the return statement

 return (kk,ll);

you're using the comma operator. By the property of the comma operator, you're not returning two values, rather you're returning the second operand of the comma operator only.

To elaborate, let's check the property of the comma operator, directly quoting the standard, C11, chapter ยง6.5.17, (emphasis mine)

The left operand of a comma operator is evaluated as a void expression; there is a sequence point between its evaluation and that of the right operand. Then the right operand is evaluated; the result has its type and value.

So, essentially, a return statement like

 return (kk,ll);

is same as

return ll;

Hope you can figure out the other case.


That said, the recommended signature for main() is int main(int argc, char*argv[]) or , at least, int main(void).

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
1

What do you expect when returning an int? C does not support tuples.

You are using the comma-operator. (ll, kk) is a single expression with the inner expressions (seperated by , - thus the name) being evaluated left to right. All but the rightmost (you can have more than two sub-expressions) results are discarded and the rightmost result is the result of the whole expression. Actually the parenthesis are unnecessary and do not change anything.

too honest for this site
  • 12,050
  • 4
  • 30
  • 52
1

You are using the comma operator.

The comma operator (represented by the token ,) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type).

Samuel Peter
  • 4,136
  • 2
  • 34
  • 42