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

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



On Wed, Jan 2, 2013 at 5:11 AM, Zbigniew Komarnicki <cblasius@gmail.com> wrote:
> On Tuesday 01 of January 2013 08:23:05 you wrote:
>> C lessons today? (There are newsgroups for C and C++ questions, but, why not?)
>
> Yes :-)
>
> 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.)

Usually, when you want to catch negative parameters, you also want to
catch positive parameters that are too large. In this case, I'm sure
you do. As someone else pointed out, that means you want to explicitly
range-check your parameters. (And your parameters should be signed,
and large enough, to allow the range checks.)

With recursive calls, I find it useful to define a "doorway" function
whose sole purpose is to do the range check and pass the valid calls
on to the recursive function. That provides the control you need on
the range check (and gives you a place to define return values for
out-of-range conditions), and it gets the range check out of the way
in the recursive part, where repeated range checks really slow things
down.

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 */ );
    ...
}

> I was very surprised when I discover that this code was compiled
> without any warning. I thought if a variable is 'unsigned int'
> then this is not allowed to assign negative value.
> That's all.
>
> Thank you very much.

Have fun!

--
Joel Rees


Reply to: