Re: Highly efficient string reversal code
Ben Bacarisse wrote:
It also has the fatal error (to me) of returning a char*. This
encourages the silly mistake of trying to print a string and its
reverse with:
printf("%s & %s\n", s, strrev(s));
In fact it is even worse than that - it fails to return the
declared object. My version returns strlen, which it needs to
evaluate to find the end of the string, and thus avoids the caller
needing to call it again. Also note that my code returns a NULL if
the passed string is NULL, and correctly handles strings of length
0 and 1.
--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home .att.net>
Try the download section.
Ben Bacarisse wrote:
Richard<rgrdev@ gmail.comwrites :
>
<snip>
>
>
Not "magic" but it has undefined behaviour on empty strings.
>
<snip>
>
>Much nicer IMO:
>>
>#include <string.h>
>>
>char * my_strrev(char *s){
> char t;
> char *e = s+strlen(s)-1;
> while(e>s){
> t = *s;
> *s++ = *e;
> *e-- = t;
> }
>}
>>
>I'm sure it breaks some sort of ISO magic,
>>
>#include <string.h>
>>
>char * my_strrev(char *s){
> char t;
> char *e = s+strlen(s)-1;
> while(e>s){
> t = *s;
> *s++ = *e;
> *e-- = t;
> }
>}
>>
>I'm sure it breaks some sort of ISO magic,
Not "magic" but it has undefined behaviour on empty strings.
encourages the silly mistake of trying to print a string and its
reverse with:
printf("%s & %s\n", s, strrev(s));
In fact it is even worse than that - it fails to return the
declared object. My version returns strlen, which it needs to
evaluate to find the end of the string, and thus avoids the caller
needing to call it again. Also note that my code returns a NULL if
the passed string is NULL, and correctly handles strings of length
0 and 1.
--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home .att.net>
Try the download section.
Comment