[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Is this OK in C++ and C?



On Wednesday 02 of January 2013 16:00:50 you wrote:

> > I wanted to prohibit user to assign negative value to a variable.
> > This variable is later passed to a recurrence function as
> > argument and of course I got segmentation fault, because
> > the function is called 4294967291 times.
> 
> I guess you mean recursive function. (Isn't English fun? Hang in there.)

Yes, you are right.
 
[...] 
> This took me a couple of years to figure out, but unsigned types are
> not for enforcing range. They are strictly for optimization. For
> example (in C, not C++):
> 
> int doorway( int p1, int * result )
> {
>     /* Note that this constant upper limit is not necessarily SHRT_MAX
> from limits.h */
>     if ( ( p1 < 0 ) || ( p1 > 0x7fff ) )
>     {   return BAD_RANGE;
>     }
>     * result = recurse( (unsigned short) p1 )
>     ...
>     return GOOD_RANGE;
> }
> 
> unsigned short recurse( unsigned short p1 )
> {
>     ...
>     intermediate = recurse( /* some expression that never goes
> negative or exceeds USHRT_MAX */ );
>     ...
> }


Thank you very much again for sharing your knowledge.

> Have fun!
> 
> --
> Joel Rees

Zbigniew


Reply to: