Scott Fluhrer
4/20/2011 5:07:00 PM
"Thomas Scrace" <tom@scrace.org> wrote in message
news:alpine.LFD.2.02.1104201524110.22103@bowman...
> On Wed, 20 Apr 2011, Scott Fluhrer wrote:
>
>>
>> "Thomas Scrace" <tom@scrace.org> wrote in message
>> news:alpine.LFD.2.02.1104201414030.21950@bowman...
>>
>> There is some sort of comparison operator in there, one would assume. If
>> not, how did your code know it went through the entire range?
>
> Yes, sorry. I do use >/< operators.
>
> The code is as follows:
>
> signed long slmax()
> {
> signed long s;
> signed long temp;
> for (s = 0, temp = -1; s > temp; ++s, ++temp) {
> ;
> }
> return temp;
> }
>
> It's the same for all the other types, the only difference is the types.
Looking at this code, the problem is not with the signed types, but the
unsigned.
When you make the s and temp unsigned, then in the first iteration:
s = 0
temp = ULONG_MAX (because that's what you get when you assign -1 to an
unsigned long)
So, s > temp is false, and so you exit immediately.
For signed types, this doesn't happen; you'll continue looping until s goes
beyond LONG_MAX, and the increment invokes undefined behavior. However, I
expect that you're not actually getting this far. Are longs 64 bits on this
platform? If it is, then this will take a *long* time (9223372036854775808
iterations; even if each iteration takes one picosecond (!), we're talking
about over 100 days).
>
> As you can see (and as I now see) in the case of an signed long it will
> cycle around and around infinitely. For the unsigned long this was of
> course not a problem. For signed shorts and signed ints it was not a
> problem because I could use a larger type (long) for the temp variable.
>
> I did not realise that signed types behaved this way.
>
> Thomas Scrace <tom@scrace.org>