Search code examples
ccomma-operator

Comma-Separated return arguments in C function


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?


Solution

  • 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.