18) Increment and Decrement¶
The concept is easy but it can still test you when there’s specifics involved, like all other concepts.
1 2 3 4 5 | |
That’s increment. It’s the equivalent of writing
x = x + 1.Decrement is the same but the other way around.
1 2 3 4 5 | |
So it’s the equivalent of writing
x = x - 1.What makes it special though is that it actually does assigning, instead of just temporarily calculating.
1 2 | |
The output of the code above is
6, and if you later call the value of x, it’ll be 5. But for this scenario:1 2 | |
The output of the code above is
6 again, but if you later call the value of x, it’ll be 6.The difference between
++x and x++ is when the assignment actually takes place. In the case of ++x, it’s the equivalent of writing x += 1; just before using it in the line. In the case of x++, it’s the equivalent of writing x += 1 after using it in the line. Give it a try.1 2 3 4 5 | |
You get the output 11, 11, 11, 12 respectively.
There is one thing to be cautious about, which is using multiple increment or decrement statements within the same line.
1 2 3 4 5 | |
If you get a question like that, you’re being too curious. Which is good, but code should be readable. That is not readable. You’re better off just incrementing them earlier or later manually using
x += 1 or y += 1 or even x++ or y++ in different lines. This is a more readable form:1 2 3 4 5 6 7 | |
In fact, not only is it more readable, but it’s also predictable. A similar question was also asked on This StackOverflow Forum. I spent a LONG time trying to figure it out, and it didn’t make sense to me.
It’s not supposed to. It’s not specified if
x++ will be evaluated first or y++ will be evaluated first. It depends on the compiler. Different ones can give the same result or a different result or do absolutely anything they want. So, yeah, if something doesn’t make sense, try to find out if there’s a pattern, and if there isn’t, then you just leave it be for a moment and focus on other things then come back with greater knowledge.