One pretty important use for me is in writing clear for loops that use
multiple counter variables. For example, suppose you have a loop like
this:
for((0 => int i), (0 => int j); i < max_value; i++, 2 +=> j)
{
// do stuff
}
Without this way of using the comma, the loop must be written like so:
0 => int j;
for(0 => int i; i < max_value; i++)
{
// do stuff
2 +=> j;
}
Okay, thats fine, and often functionally equivalent, but its less
maintainable. For example, you can't use the continue keyword in the
loop, unless you also add the j += 2; part each time you continue.
Also, you can't really tell how the loop iterates just by looking at
the first line. In the comma-enabled version, its easy to see that this
loop iterates i by 1 up to max_value, and j by 2 up to max_value * 2.
In the second version, you need to look at the end of the loop block in
addition to any continue statements to see how the loop iterates--who
cares for simple loops, but nasty with crazy nesting loops.
spencer
Quoting Kassen
2008/6/28 Jukka Akkanen
: This seems to be similar to the comma operator in C, which lets you use multiple comma-separated sub-expressions in a context where only a single expression is allowed. An expression using the comma operator evaluates to the value of the last sub-expression. Note that the comma operator is very different from how && works.
Got it.
How and where is this useful?
Thanks!
Kas.