++ Past Maximum Value
Hi all,
I've been searching around for an answer to this topic, sorry if it is already mentioned.
I was wondering if there is a standard behavior for using the increment(++) operator on an integer at the maximum value. OK, not sure if that was clear.
The maximum possibilites of an unsigned int composed of 4-bytes is 4294967296 so the highest numerical value is 4294967295. Now when I increment it, on GCC it reverts to 0. Is this standard behavior or does it depend on the compiler?
Thanks
Unsigned integers obey the laws of modular arithmetic mod 2^n where n is the number of bits in the type. (Section 3.9.1 paragraph 4 in the C++ standard) Increment adds one to the value, so wrapping around to 0 is indeed what modular arithmetic would dictate.
A similar question, something I've never heard a straight answer for.
In the case of a wrap around, is it guaranteed that none of the bits 'next' to the number in memory are effected?
ex.
Does that actually happen in memory, or are things smart enough not to overrun to other memory?
In the case of a wrap around, is it guaranteed that none of the bits 'next' to the number in memory are effected?
ex.
11111111 + 00000001 == 1 00000000 ^|-------| oops reset to 0
Does that actually happen in memory, or are things smart enough not to overrun to other memory?
Considering that these operations usually happen in registers and not memory, it would be very difficult for it such a kind of thing to happen even by accident. But no, it shouldn't happen.
Quote:Original post by TelastynActually I'd say it's dumb enough not to do so..
Does that actually happen in memory, or are things smart enough not to overrun to other memory?
In any case, it won't happen and it is not allowed by the standard.
Most datatypes are processed in fixed-sized chunks by the processor. And if the processor can't handle them natively (lets say a 64-bit integer on a 32-bit system) the overflow (carry) is passed over to the next value manually.
No, the CPU pulls the numbers from memory adds the two together and puts the result back. The overflow bit is stored / lost what ever, in the CPU. Very basicaly speeking.
Actually, the specification doesn't specify the number of bits used for char, short, int, and long. The specification only states that char <= short <= int <= long. But, yes, the specification also states that when you increment past the size of the variable, it'll wrap around, depending on if its signed or not. (Signed variables would loop to the most negative number possible)
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement