c++ - Strange comma operator behaviour -
this question has answer here:
- why these constructs (using ++) undefined behavior? 12 answers
- undefined behavior , sequence points 3 answers
void foo() { int a[5], c = 2; (int = 0; < 5; i++) a[i] = 0; int res = (c--, a[c]++, c++) + (c++, a[c]--, c--); (int = 0; < 5; i++) cout << << ": " << a[i] << endl; }
the code above print:
0 : 0 1 : 1 2 : -1 3 : 0 4 : 0
instead of:
0 : 0 1 : 1 2 : 0 3 : -1 4 : 0
this because operations order in generated code following:
// first parentheses c--; a[c]++; // second parentheses c++; a[c]--; // , last operation res = c++ + c--;
the question is: why operations not run expected (i.e. 3 operations in 1 parentheses , 3 operations in other)?
order of operations not guarenteed in between sequence points. sequence point found @ semi-colon.
wouldn't a[c-1]++;
better (c--, a[c]++, c++)
anyway? why write main ram new value c
4 times when don't keep value other calculation?