2

I came across the following for loop with a very unusual condition

int main( int argc, const char* argv[] ) {
    for ( int i = 0 ; i < ( 10, 20 ) ; i++ ) {
        cout << i << endl;
    }
}

This source code compiled successfully. It executed the loop with i with values from 0 to 19 (the 10 in the expression (10, 20) seems to have no effect on the number of iterations).

My question:
What is this condition syntax? Why doesn't it cause a compile error?

EDIT:
The bigger picture: this questions started with a bug, the original condition was supposed to be i < std::min( <expr A>, <expr B> ) and for some reason I omitted the std::min.

So, I was wondering why the code compiled in the first place. Now I see the bug is a legit (albeit useless) syntax.

Thanks!

Richard Chambers
  • 16,643
  • 4
  • 81
  • 106
Shai
  • 111,146
  • 38
  • 238
  • 371

3 Answers3

7

It is the comma operator. It evaluates both sides of the expression, and returns the right one.

So, expression (10, 20) does nothing, but returns '20'.

See also

Community
  • 1
  • 1
nothrow
  • 15,882
  • 9
  • 57
  • 104
3

(10, 20) means evaluate the integer 10, then evaluate 20, then return 20 (the rightmost). So it just means 20.

The comma operator is often useful in for loops, as it allows things such as x = 0, y = 1 (i.e. two assignments in one expression), but here it's useless.

teppic
  • 8,039
  • 2
  • 24
  • 37
0

, operator in c++ work as a binary operator which checks first value, discard it and return the next value. In short.

for(int i=0;i<(10,20);i++) will be equal to for(int i=0;i<20;i++)