Earlz Earlz - 1 month ago 17
C Question

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

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

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.