Purpose of the Comma Operator

I think that the comma operator returns the rightmost expression so 10, 12, 15 returns 15. However, I have a few questions about the operator.

Firstly, are commas in initialisation lists comma operators. I can see that this would not cause a problem, but on the other hand it doesn't achieve anything either as far as I can see.

Also, I can think of one acceptable (I think!) use of the comma operator, (and one bad one). Are there any other important uses of it that I'm missing?

1
2
for (int ctr1=0, ctr2 = 0; ctr1<3 && ctr2<3; ctr1++, ctr2++)
   ; // etc 


(The bad one is:
1
2
int a = 1, b;
b = a++, 2; // assigns 2 to b and increments a 

which as well as being a contrived example, this seems to me to be woefully messy ;) .)
Last edited on
Not all commas are equal.

Initialization lists and argument lists are not expressions; hence, their commas are not comma operators.

While you can, it is best not to mess around with the comma operator.

Hope this helps.
The only valid use I've ever seen of the comma operator was in some template metaprogramming code that determined at compile time whether or not operator<< existed for a given type. Unfortunately I cannot remember the actual code.
OK then. I just wondered why the operator is there at all. Maybe I'll come across a proper use of it someday ;)

Thanks for the help everyone.
I think using the comma operator is valid in the initialization and repeat parts of for loops. You don't need the values of the expressions there, just the side effects, and there are situations in which you might want to have multiple statements there. I know this is avoidable in most cases, but in some cases the alternative is just ugly.
That makes sense: I can see where one would use the comma operator when the values aren't needed. As for situations when the value is needed, I think that using the comma operator would end up being too messy (as in my second example above). I think I'm just about clear on it now anyway.

Thanks for the help.
Last edited on
comma operator can be usefull if you remember, that the following will compile:

 
return function(), 1


even if function does not return anything (void).


At least I remember, that I saw this use once in some crazy ASSERT-macro-define-magic in a windows header file.. but I don't remember the details.

But yea.. at the end of the day, comma operator is one of those things you tell about in parties and everyone says: "REALLY? You saw it in the wild??"
Ok. I can see how that might be useful on occasion...

So thanks again for the info everyone :)

PS: imi, sadly few of my friends would appreciate references to obscure C++ operators ;) Shame
Topic archived. No new replies allowed.