Re: reverse a string
- From: Tim Rentsch <txr@xxxxxxxxxxxxxxxxxx>
- Date: Fri, 02 Oct 2009 13:25:56 -0700
Richard Heathfield <rjh@xxxxxxxxxxxxxxx> writes:
In <kfnzl8c3qv5.fsf@xxxxxxxxxxxxxxxxxxxxxxxxxxxx>, Tim Rentsch wrote:
Richard Heathfield <rjh@xxxxxxxxxxxxxxx> writes:<snip>
int si_digital_root(const char *s, size_t start, size_t end)
{
int root = 0;
assert(start <= end); /* A */
assert(s != NULL); /* B */
assert(strlen(s) >= end); /* C */
while(start <= end)
{
assert(isdigit(s[start])); /* D */
root += s[start] - '0';
root %= 10;
}
assert(root >= 0 && root <= 9); /* E */
return root;
}
A and B are simple and cheap checks that the constraints have been
observed. C is a slightly more expensive check, since it's O(n).
Not quite. If we take n to be (end-start)+1, or even just end+1,
check C is O( infinity ).
It also involves undefined behavior if the array [starting at *s]
is not null terminated.
True enough. Can you think of a way to test this constraint (which I
didn't spell out explicitly, but which is implied by the use of
"string" in the docs.
That's a fair reason for wanting to compile it out of production
code, [snip]
Seems more appropriate to take it as a fair reason to re-write
the assertion C.
How would you rewrite it to include a test for s's null-termination,
without yourself constructing a pointer that invokes undefined
behaviour?
If I were writing an assert() for the condition that I think
you want to test, I expect I'd write it as
assert( memchar( s, 0, end ) == 0 );
or perhaps as
assert( memchar( s, 0, start ) == 0 );
and rely on the digits check assertion to test the
characters between 'start' and 'end'.
More likely, though, I wouldn't write the test at all,
since the digits are checked in the loop, and there
doesn't seem to be much point in excluding arguments
that happen to have a zero in the first [0..start)
positions of the *s array. Or, perhaps I would
write an additional function
int
si_digital_root_safe( const char *s, size_t start, size_t end ){
assert( memchar( s, 0, end ) == 0 );
return si_digital_root( s, start, end );
}
and give client code a choice of which function to call.
Having the choice available reduces the impetus for
wanting to remove this assertion for production code.
.
- Follow-Ups:
- Re: reverse a string
- From: Keith Thompson
- Re: reverse a string
- References:
- Re: reverse a string
- From: Tim Rentsch
- Re: reverse a string
- From: Richard Heathfield
- Re: reverse a string
- Prev by Date: Re: Maybe you should consider this
- Next by Date: Re: About the container library
- Previous by thread: Re: reverse a string
- Next by thread: Re: reverse a string
- Index(es):
Relevant Pages
|