57
i++
(programming.dev)
Welcome to Programmer Humor!
This is a place where you can post jokes, memes, humor, etc. related to programming!
For sharing awful code theres also Programming Horror.
That won't work if
i
is unsigned.If you're in a language that doesn't care about integer overflow it does. Tried it in C and turned off compiler optimization for good measure. Still counted fine. It's not a good idea, but it does work.
Huh. I had to think about it for a moment, but you're right. If the two's-complement representation of -1 is reinterpreted as an unsigned integer and added to another unsigned integer of the same size, it'll wrap all the way around, effectively adding -1.
It's an interesting property of two's complement that you don't usually think about when you're using a strongly-typed language where such shenanigans aren't allowed. I imagine compiler and assembly people are well aware of it, though.
For anyone following along and wondering how this works, here's a quick explanation. Suppose you've got a device that can calculate the sum of any two integers between 0 and 99. If it calculates a sum greater than 99, it wraps around. For example, if you tell it to calculate 99 + 1, you get 0.
Now, suppose you want to add negative integers with this thing. You'll pretend that 99 actually means -1, 98 actually means -2, and so on, for every number between 50 and 99. 0 through 49 will represent positive numbers, and 50 through 99 will represent negative numbers.
So, what if you add 5 and -1? Well, 5 is itself, -1 is 99, and the device wraps around when it calculates a sum greater than 99, so if you add 5 and 99, you get…4! It correctly adds your pretend negative numbers without you having to do anything extra.
This is pretty much the same as how computers work, except binary instead of decimal.
That stuff working is pretty much the point of two's complement: You can use the same circuitry for addition and subtraction that's why everyone settled on it.
Hey, thanks for that explanation! I didn't understand what was going on and that clarified it.