C++ -- return x,y; What is the point?

Earlz picture Earlz · Mar 29, 2010 · Viewed 24.9k times · Source

I have been programming in C and C++ for a few years and now I'm just now taking a college course in it and our book had a function like this for an example:

int foo(){
  int x=0;
  int y=20;
  return x,y; //y is always returned
}

I have never seen such syntax. In fact, I have never seen the , operator used outside of parameter lists. If y is always returned though, then what is the point? Is there a case where a return statement would need to be created like this?

(Also, I tagged C as well because it applies to both, though my book specifically is C++)

Answer

Justin Ethier picture Justin Ethier · Mar 29, 2010

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)