C function return arguments

Completing the C programming test, I was asked a question about the expected output of a function that appears to return two values. It was structured as follows:

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

The question took me by surprise and essentially thought that, if possible, the first argument would be passed to the caller.

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

Why is he acting like that and why?

+4
source share
4 answers

The comma operator evaluates a number of expressions. The comma group value is the value of the last item in the list.

In an example showing that the leading constant expression 44 has no effect, but if the expression has a side effect, this will happen. For instance,

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

In this case, the program will print β€œwe are done” and then return 66.

+5
source

In your code

  return (44,66); 

does (incorrectly) use a comma property. Here, it practically discards the first (left) operand of the operator , and returns the value of the second (right operand).

To quote the C11 standard, chapter Β§6.5.17, comma operator

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

In this case, this is the same as the entry.

  return 66; 

However, FWIW, the left-side operand is evaluated as a void expression, which means that if there is any side effect of this evaluation, this will happen as usual, but the result of the whole expression of the expression associated with the comma operator will have the type and value of the operand evaluation right side.

+3
source

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

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

Read more about the comma .

+2
source

The Coma operator always returns the rightmost operand value when multiple comma operators are used in an expression. Obviously, he will return 66.

+1
source

All Articles