Up until today I thought I understood C++ operators and precedence. I give you the following simple code:
int i = 0, j = 0
i++;
j++;
cout << i << ' ' << j << endl;
Naturally, we expect the output values for i
and j
to be 1 and 1, respectively. Now what happens if we try to put our increments into one line?
int i = 0, j = 0
i++ && j++;
cout << i << ' ' << j << endl;
My reasoning here is that a boolean operator has no effect on the output. But our output is surprisingly i = 1
and j = 0
? So what's going on here?
What's more strange to me is that by switching from postfix increment to prefix increment or using another boolean operator, the result is as expected. I.e:
//Expected i=1, j=1
++i && ++j;
//Expected i=1, j=1
i++ || j++;
P.S. I know that the right use case to update both variables in one line looks like this:
i++, j++;
But curiosity got the best of me and now I'm wondering why using the boolean AND
operator has the unsurprising result.