Again, little to add here because pre- and post- increment and decrement are simply features of the language. But there’s a funny thing you’ll sometimes see in old-school code.
The rules of these operations are pretty straightforward…
a = ++b; // Add 1 to value of b, assign back to b, also assign to a a = --b; // Subtract 1 from value of b, assign back to b, also to a a = b++; // Assign value of b to a, then add 1 and assign back to b a = b--; // Assign value of b to a, subtract 1 and assign back to b
You’ll see these with pointers and counters a lot, often with the “a=
” part left off, just performing operations on a single variable. Often the third element of a for
loop, e.g. i++
.
Python doesn’t have these operators, preferring a += 1
or a -= 1
instead, so they’re a little strange if just coming into C from that language.
Most modern CPUs support all of these operations down at the instruction level; you often get any of these increments or decrements “free” as part of another operation. That wasn’t always true though. If I recall correctly, I think the Motorola 68000 (maybe others) only had pre-decrement and post-increment, and the other combinations required extra cycles as they’re performed “manually.” That chip’s DBRA opcode (decrement and branch if not zero) was particularly efficient for loops.
So…in old code, or even in modern code written by folks with habits ingrained in that era…you may see programmers prostrating themselves to structure program flow into a do-while
loop (decrementing and testing against zero at the end)…trying to optimize the code manually, because compilers sucked…rather than a simpler, more readable (and likely just as efficient now) implementation.
I still do this all the time, but mostly for nostalgia’s sake.
Text editor powered by tinymce.