2

Possible Duplicate:
C++ Comma Operator

I am initializing an array with

int main()
{
    int arr[3]= { (1,3), 2, 4 };
    cout << arr[0] << " " << arr[1] << " " << arr[2] << endl;
}

I thought it would give a compile time error but it is running fine. The array is initialized with values 3,2,4 and output is also 3 2 4.

Can someone explain what is happening here ?

Community
  • 1
  • 1
manyu
  • 475
  • 2
  • 6
  • 12
  • A vote to reopen should include an explanation of some way this question is different from the duplicate. If you can't think of one, don't reopen. – Ben Voigt Feb 28 '12 at 14:37

2 Answers2

4

You're looking at the comma operator there. Basically, the expression:

1,7

will evaluate 1 but "return" 7.

That particular form you have (as well as mine above) is not that useful but you can do things like:

x = a++, 1;

to both increment a and set x to 1 (the usefulness comes from side effects).

You will have seen this before without necessarily realising it:

for (i = 0, j = 0; i < 4; i++, j++) ...
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
2

The same reason why:

int x = (1,3);
assert(x==3);

happens.

That's how the comma operator works. It "returns" the last expression, while (potentially) evaluating both.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625