C++ -- return x,y; What is the point?
According to the C FAQ:
Precisely stated, the meaning of the comma operator in the general expression
e1 , e2
is "evaluate the subexpression e1, then evaluate e2; the value of the expression is the value of e2." Therefore, e1 had better involve an assignment or an increment ++ or decrement -- or function call or some other kind of side effect, because otherwise it would calculate a value which would be discarded.
So I agree with you, there is no point other than to illustrate that this is valid syntax, if that.
If you wanted to return both values in C or C++ you could create a struct
containing x
and y
members, and return the struct instead:
struct point {int x; int y;};
You can then define a type and helper function to allow you to easily return both values within the struct
:
typedef struct point Point;Point point(int xx, int yy){ Point p; p.x = xx; p.y = yy; return p;}
And then change your original code to use the helper function:
Point foo(){ int x=0; int y=20; return point(x,y); // x and y are both returned}
And finally, you can try it out:
Point p = foo();printf("%d, %d\n", p.x, p.y);
This example compiles in both C and C++. Although, as Mark suggests below, in C++ you can define a constructor for the point
structure which affords a more elegant solution.
On a side note, the ability to return multiple values directly is wonderful in languages such as Python that support it:
def foo(): x = 0 y = 20 return x,y # Returns a tuple containing both x and y>>> foo()(0, 20)
The comma in parameter lists is just there to separate the parameters, and is not the same as the comma operator. The comma operator, as in your example, evaluates both x and y, and then throws away x.
In this case, I would guess that it is a mistake by someone who tries to return two values, and didn't know how to do it.
The comma operator is primarily used in for
statements like so:
for( int i=0, j=10; i<10; i++, j++ ){ a[i] = b[j];}
The first comma is not a comma operator, it's part of the declaration syntax. The second is a comma operator.