comma operator: dangerous or useful?

Has anyone ever used the comma operator in their programs?

 
i1 = (i2 = 2, i3 = 3);


I mean using it in the context of using it for a meaningful reason (speed, memory, or whatever) such that it made more sense than...

1
2
3
i2 = 2;
i3 = 3;
i1 = i3;


also, is the C++ standard ever going to enforce any order on left to right evaluation of expressions, or will it always be up to the vendor compiler whether i2 or i3 gets evaluated first?

By the way, my VC++ IDE debugger refuses to give me a watch value on
 
(i2=2, i3=3)

it gives me a syntax error even though it's a legal C++ expression. Funny.
You could also do this:

1
2
i2 = 2;
i1 = i3 = 3;
is the C++ standard ever going to enforce any order on left to right evaluation of expressions, or will it always be up to the vendor compiler whether i2 or i3 gets evaluated first?


The comma operator is one of the few operators with for sure left to right evaluation of the operands

The comma operator is one of the few operators with for sure left to right evaluation of the operands


I thought I read somewhere to never call a function like this

i=1;
count123(i++, i++, i++);

because you don't know if you are calling: count123(1, 2, 3)
or: count123(3, 2, 1)

because there's no guarantee parameters will be evaluated left to right?

That is not the comma operator, that is the comma used for separating arguments.
Some symbols have many different meanings in C++ ( think of * )
I see what you mean. count123(1,2,3) would be same as count(3) if those commas were operators. Thanks Bazzy ...and thanks also Firedraco for your alternate suggestion.
Last edited on
In general the operator is useful only in very specific circumstances where multiple things need to be done in a single line of code (largely for syntactic reasons, though I cannot come up with one off the top of my head).

I have also seen the comma operator used in template metaprogramming to detect, for example, whether or not a class provides an ostream operator.
(I'm not even going to bother going into the details of that).
Topic archived. No new replies allowed.