Mail Archives: djgpp/2000/01/08/01:57:08
Michael Farnham <MCFARNHAM AT prodigy DOT net> wrote in message
news:854fv0$a7bo$1 AT newssvr03-int DOT news DOT prodigy DOT com...
>
>
> Chris Underwood <underwoodc AT logica DOT nospam DOT com> wrote in message
> news:854cnj$453 AT romeo DOT logica DOT co DOT uk...
> >
> > >Rob McCrea (r_mccrea AT hotmail DOT com) wrote:
> > >: My expression won't recognize the overflow...
> > >:
> > >: while ((s+1) > s) s++;
> > >:
> > >: is an infinite loop. What's up with that?
> > >: Apparently the condition is being evaluted as (1>0).
> > >: That's not right is it? I'm compiling with gpp -Wall
testsize.cpp -o
> > >: testsize.exe.
> > >:
> > >: Please, can someone explain why its not acting like a computer?
> >
> >
> > I'm not sure exactly what you're claiming is wrong here, but you might
> not
> > realise that sooner or later, given that 's' is likely an integer of
some
> > size or another, it'll wrap around, and your loop will exit. For
example,
> if
> > 's' is an unsigned char you will loop until s = 255, then s+1 will be
256
> > which overflows and wraps round to 0. (0 > 255) is false, and you'll
exit
> > the loop.
> >
> > Chris
> >
> >
>
I have done some code testing and have come to some conclusions.
* With no optimizations turned on and when s is an int the loop
quits when s = INT_MAX (from limits.h or climits).
* When s is a char s + 1 is implicitly converted to int and the
loop is infinite.
* If s is a type where the maximum value is less than INT_MAX
(e.g. CHAR_MAX < INT_MAX), then s + 1 will be converted to an
int and the loop will be infinite. If s is an int then the
loop will terminate when s = INT_MAX.
* If the only purpose of this loop is to identify the maximum
value for the type then it would be easier to use the value
defined in the standard header file limits.h (C) or climits (C++).
Regards
Mike
- Raw text -