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)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)