4
I used the following code snippet:
bool plus = false;
int index = 0;
index = plus ? index++ : index--;
the index result is 0 and do not know why, when I do the way below it works:
index += plus ? 1 : -1;
Someone has an explanation for this?
I guess what I wanted to do was
index = plus ? index+1 : index-1;
instead of using pre- and post-increment operators– Isac
Complementing what @Isac said: the post-decrement operator works like this: it takes the value of the variable, puts a copy of that value to be used in the operation and increments/decreases the variable, keeping the copy intact; then it executes the operation. In your case, the following occurs: (1) copies the value of
index
(which is 0) on something temporary (2) increments/decreasesindex
(which goes to +1 or -1), keeping your copy intact (3) assigns toindex
the operand (that is 0), which ultimately cancels the side effect of the post increment/decrease operator– Jefferson Quesado
Now I realized, I had already solved with the second example of the question, but to test I used the pre-aincrement/ decrement and it worked, thank you very much for the explanation!
– Roberto Gomes