Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comma-Separated return arguments in C function [duplicate]

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?

like image 406
user1556232 Avatar asked Aug 19 '15 11:08

user1556232


4 Answers

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.

like image 193
Tyler Durden Avatar answered Nov 17 '22 05:11

Tyler Durden


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.

like image 34
Sourav Ghosh Avatar answered Nov 17 '22 04:11

Sourav Ghosh


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.

like image 42
Jabberwocky Avatar answered Nov 17 '22 05:11

Jabberwocky


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

like image 1
piyush Avatar answered Nov 17 '22 05:11

piyush