Here's an example
#include <iostream>
using namespace std;
int main()
{
int x = 0;
cout << (x == 0 ? x++ : x) << endl; //operator in branch
cout << "x=" << x << endl;
cout << (x == 1 || --x == 0 ? 1 : 2) << endl; //operator in condition
cout << "x=" << x << endl;
return 0;
}
output:
0
x=1
1
x=1
I understand the output, but is this undefined behaviour or not? Is the order of evaluation guaranteed in either case?
Even if guaranteed, I'm quite aware using increment/decrement can quickly become an issue for readability. I only ask as I saw similar code and was immediately unsure, given there are lots of examples of ambiguous/undefined use of increment/decrement operators, such as...
C++ does not define the order in which function parameters are evaluated. ↪
int nValue = Add(x, ++x);
The C++ language says you cannot modify a variable more than once between sequence points. ↪
x = ++y + y++
Because increment and decrement operators have side effects, using expressions with increment or decrement operators in a preprocessor macro can have undesirable results. ↪
#define max(a,b) ((a)<(b))?(b):(a) k = max( ++i, j );