++ Past Maximum Value

This topic is 4885 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

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

Yes it is.

Share on other sites
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.

Share on other sites
Thanks for the quick replies!

Share on other sites
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.
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?

Share on other sites
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.

Share on other sites
Quote:
 Original post by TelastynDoes that actually happen in memory, or are things smart enough not to overrun to other memory?
Actually I'd say it's dumb enough not to do so..
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.

Share on other sites
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.

Share on other sites
Ah. Interesting. Many thanks.

Share on other sites
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)

1. 1
2. 2
3. 3
Rutin
15
4. 4
5. 5

• 10
• 9
• 9
• 11
• 11
• Forum Statistics

• Total Topics
633685
• Total Posts
3013322
×