0

So, I'm doing homework. I've encountered something I haven't seen before and cannot find a decent explanation of what it does. Basically,

Object object;
...
while((value1, value2) = function(object)) {
    object.foo(value1, value2);
}

The (value1, value2) in the while statement really throws me. Any ideas?

JDong
  • 2,304
  • 3
  • 24
  • 42
lambgrp425
  • 706
  • 1
  • 8
  • 20
  • 1
    You'll find answers by searching for "comma operator". [Here's one](http://stackoverflow.com/q/54142/1016716) – Mr Lister Jul 06 '13 at 05:05
  • Haven't tried. This was part of a specification. Not sure what to make of it – lambgrp425 Jul 06 '13 at 05:06
  • 1
    THe others answered what it does. I just want to comment- never do this. Its confusing and brings no value, there's cleaner ways to write it. This is basically a stupid C++ tricks question. – Gabe Sechan Jul 06 '13 at 05:10
  • Thanks for pointing me in the right direction! – lambgrp425 Jul 06 '13 at 05:11
  • @GabeSechan: I agree with everything you said. But I suspect it may be a failed translation from another language where multiple values can be returned. If the original code has `return 1,2;` inside `function()` one may think that you can call the function like `(a,b) = function();`. – Martin York Jul 06 '13 at 05:14

1 Answers1

1

Its a comma operator.

The result of the comma operator is the last value (the others are evaluated and discarded).

while((value1, value2) = function(object)) {
    object.foo(value1, value2);
}

If value1 is just a variable and not an expression then it is equivalent too:

while(value2 = function(object)) {
    object.foo(value1, value2);
}

If value1 is an expression then it is evaluated each time around the loop. The result is discarded, but if the expression has side effects these will take effect.

Martin York
  • 257,169
  • 86
  • 333
  • 562