unsigned interger overflow

Alexandr Druzhinin drug2004 at bk.ru
Wed Oct 2 08:32:56 PDT 2013


02.10.2013 12:41, Jonathan M Davis пишет:
> On Wednesday, October 02, 2013 12:32:24 Alexandr Druzhinin wrote:
>> Is it safe to replace code:
>>
>> uint index;
>> // do something
>> index++;
>> if(index == index.max)
>> index = index.init;
>>
>> by the following code
>> uint index;
>> // do something
>> index++; /// I use unsigned int so uint.max changed to 0 automagically
>
> Well, not quite. Your first one skips uint.max. It goes from uint.max - 1 to 0,
> whereas the second one goes from uint.max to 0. So, they're subtly different.
> But yes, incrementing the maximum value of an unsigned integral type is
> guaranteed to wrap around to 0. Signed integers are of course another matter
> entirely, but it's guaranteed to work with unsigned integers.
>
> - Jonathan M Davis
>
Thanks for clarification.


More information about the Digitalmars-d-learn mailing list