Re: Mystery: static variables & performance
"CBFalconer " <cbfalconer@yah oo.com> wrote in message
news:4036B315.B 8FE1A7E@yahoo.c om...[color=blue]
> Peter Nilsson wrote:[/color]
....[color=blue][color=green][color=darkred]
> > > >>> int strcmp(const char *s1, const char *s2) {
> > > >>> while ( *s1 == *s2 && *s1 )
> > > >>> ++s1, ++s2;
> > > >>>
> > > >>> return *s1 - *s2;
> > > >>> }[/color][/color]
>...[color=green]
> >
> > The most robust answer would seem to be...
> >
> > return (unsigned char) *s1 > (unsigned char) *s2
> > - (unsigned char) *s1 < (unsigned char) *s2;[/color][/color]
Oops...
return ((unsigned char) *s1 > (unsigned char) *s2)
- ((unsigned char) *s1 < (unsigned char) *s2);
[color=blue][color=green]
> >
> > or...
> >
> > return (unsigned char) *s1 < (unsigned char) *s2 ? -1
> > : (unsigned char) *s1 > (unsigned char) *s2;[/color]
>
> Why cast to unsigned char?[/color]
Because that is the specification for strcmp().
[color=blue]
> If native chars are signed, I would
> want this routine to respect that.[/color]
If we weren't talking about strcmp, you would be free to do that. But you
may get some unexpected surprises, e.g. "a" > "aé".
[color=blue]
> Casts are usually a sign of evil doings.[/color]
You can do the same thing without casts, if you like.
--
Peter
"CBFalconer " <cbfalconer@yah oo.com> wrote in message
news:4036B315.B 8FE1A7E@yahoo.c om...[color=blue]
> Peter Nilsson wrote:[/color]
....[color=blue][color=green][color=darkred]
> > > >>> int strcmp(const char *s1, const char *s2) {
> > > >>> while ( *s1 == *s2 && *s1 )
> > > >>> ++s1, ++s2;
> > > >>>
> > > >>> return *s1 - *s2;
> > > >>> }[/color][/color]
>...[color=green]
> >
> > The most robust answer would seem to be...
> >
> > return (unsigned char) *s1 > (unsigned char) *s2
> > - (unsigned char) *s1 < (unsigned char) *s2;[/color][/color]
Oops...
return ((unsigned char) *s1 > (unsigned char) *s2)
- ((unsigned char) *s1 < (unsigned char) *s2);
[color=blue][color=green]
> >
> > or...
> >
> > return (unsigned char) *s1 < (unsigned char) *s2 ? -1
> > : (unsigned char) *s1 > (unsigned char) *s2;[/color]
>
> Why cast to unsigned char?[/color]
Because that is the specification for strcmp().
[color=blue]
> If native chars are signed, I would
> want this routine to respect that.[/color]
If we weren't talking about strcmp, you would be free to do that. But you
may get some unexpected surprises, e.g. "a" > "aé".
[color=blue]
> Casts are usually a sign of evil doings.[/color]
You can do the same thing without casts, if you like.
--
Peter
Comment