0
void foo() {
   int a[5], c = 2;
   for (int i = 0; i < 5; i++)
      a[i] = 0;
   int res = (c--, a[c]++, c++) + (c++, a[c]--, c--);
   for (int i = 0; i < 5; i++)
      cout << i << ": " << a[i] << endl;
}

The code above will print:

0 : 0
1 : 1
2 : -1
3 : 0
4 : 0

Instead of:

0 : 0
1 : 1
2 : 0
3 : -1
4 : 0

This is so because the operations order in generated code is the following:

// first parentheses
c--;
a[c]++;
// second parentheses
c++;
a[c]--;
// and only then the last operation
res = c++ + c--;

The question is: why operations do not run as expected (i.e. all three operations in one parentheses and then all three operations in other)?

Mikhail Melnik
  • 966
  • 9
  • 19
  • 2
    Operands of `+` are **not** ordered. There's no saying of which is computed first. – n. m. could be an AI Apr 25 '13 at 16:18
  • 1
    @n.m. Or even that one _is_ computed first. The compiler can compute part of one, then part of another, then return to the first, etc. (Which is apparently what is happening here.) – James Kanze Apr 25 '13 at 16:27

1 Answers1

1

Order of operations is not guarenteed in between sequence points. An sequence point is generally found at a semi-colon.

Wouldn't a[c-1]++; be better than (c--, a[c]++, c++) anyway? Why write to main RAM a new value for c 4 times when you don't keep the value for some other calculation?

David G
  • 94,763
  • 41
  • 167
  • 253
jmucchiello
  • 18,754
  • 7
  • 41
  • 61