Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can 'return' return multiple values in C? [duplicate]

Tags:

c++

c

Possible Duplicate:
C++ — return x,y; What is the point?

Here's a piece of code that executes perfectly in C.

int a=3,b=4,x,y;
x=a+b;
y=a*b;
return(x,y);

This function returns 12. Can someone please explain.

like image 484
Vish Avatar asked Nov 23 '25 09:11

Vish


1 Answers

This is because you (inadvertently) use the comma operator, whose value is that of the last expression included. You can list as many expressions as you like, separated by the comma operator, the result is always that of the last expression. This is not related to return; your code can be rewritten like

int tmp = (x, y); // x = 7, y = 12 -> tmp is assigned 12
return tmp;

[Updated] You don't usually need brackets around the list, but here you do, due to the assignment operator having a higher precedence than comma - kudos to @Draco for pointing it out.

like image 161
Péter Török Avatar answered Nov 24 '25 22:11

Péter Török