8

While completing a C programming test, I was given a question regarding the expected output from a function which seem to return two values. It was structured as follows:

int multi_return_args(void)
{
 return (44,66);
}

The question caught me by surprise and inherently thought that if possible the first argument would be passed to the caller.

But after compiling it, the result is 66 instead. After a quick search I couldn't find anything about structuring a return statement like this so was wondering if some could help me.

Why does it behave like this and why?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
user1556232
  • 117
  • 1
  • 5

4 Answers4

10

The comma operator evaluates a series of expressions. The value of the comma group is the value of the last element in the list.

In the example you show the leading constant expression 44 has no effect, but if the expression had a side effect, it would occur. For example,

return printf( "we're done" ), 66;

In this case, the program would print "we're done" and then return 66.

Tyler Durden
  • 11,156
  • 9
  • 64
  • 126
  • Thanks for the explanation, I haven't really used the comma property operator in such a way before. I started coming up with some really convoluted ideas how it was working. More examples on how its used can be shown in this thread [What does the comma operator \`,\` do in C](http://stackoverflow.com/questions/52550/what-does-the-comma-operator-do-in-c) – user1556232 Aug 19 '15 at 12:14
6

In your code,

 return (44,66);

is making (mis)use of the comma operator property. Here, it essentially discards the first (left side) operand of the , operator and returns the value of that of the second one (right operand).

To quote the C11 standard, chapter §6.5.17, Comma operator

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.

In this case, it is same as writing

 return 66;

However, FWIW, the left hand side operand is evaluated as a void expression, meaning, if there is any side effect of that evaluation, that will take place as usual, but the result of the whole expression of the statement involving the comma operator will be having the type and the value of the evaluation of the right hand side operand.

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

This will return 66. There is nothing special about returning (44,66).

(44,66) is an expression that has the value 66 and therefore your function will return 66.

Read more about the comma operator.

Community
  • 1
  • 1
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
1

Coma operator always returns the value of the rightmost operand when multiple comma operators are used inside an expression. It will obviously return 66.

piyush
  • 868
  • 13
  • 29