Can 'return' return multiple values in C? [duplicate]
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.
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.
Edit : This answers the title Q, viz 'can return return multiple values' Not exactly. You can
- return the second variable by using reference (or pointer) parameter
- otherwise, create a new class or struct containing x and y and return an instance of this new class
No, you cannot return multiple values simply by using (x, y)
— this is not a tuple, as you might expect from other languages, but a bracketed use of the comma operator, which will simply evaluate to y
(which will, in turn, be returned by the return
).
If you want to return multiple values, you should create a struct
, like so:
#include <stdio.h>
struct coordinate
{
int x;
int y;
};
struct coordinate myfunc(int a, int b)
{
struct coordinate retval = { a + b , a * b };
return retval;
}
int main(void)
{
struct coordinate coord = myfunc(3, 4);
printf("X: %d\n", coord.x);
printf("Y: %d\n", coord.y);
}
This shows the full syntax of using a struct, but you can use typedef
if you prefer something like:
typedef struct
{
int x;
int y;
} coordinate;
coordinate myfunc(int a, int b)
{
coordinate retval = { a + b , a * b };
return retval;
}
// ...etc...
The answer to your question is "no, return cannot return multiple values". Here you see the result of the evaluation of the legal expression x,y
, which is y
i.e. 3*4 = 12.
The comma operator is just a binary operator. The right-most value is returned.
That's the comma operator. It evaluates its left side, then evaluates its right side, and its resulting value is the right side.
So, return(x,y)
is the same as return y
, since evaluating x
has no side-effects.
The only way to "return multiple values" in C is to return a struct by value:
#include <stdio.h>
typedef struct {
int sum;
int product;
} sumprod;
sumprod get_sum_and_product(int x, int y) {
sumprod ret = {x + y, x * y};
return ret;
}
int main() {
sumprod values = get_sum_and_product(3,4);
printf("sum is %d, product is %d\n", values.sum, values.product);
}
精彩评论