Style (was: C-DATABASE B-PLUS a quick look)

T. William Wells bill at twwells.uucp
Fri Jan 6 04:28:13 AEST 1989


In article <2581 at ficc.uu.net> peter at ficc.uu.net (Peter da Silva) writes:
: In article <2537 at xyzzy.UUCP>, throopw at xyzzy.UUCP (Wayne A. Throop) writes:
: >     #include <ctype.h>
: >     char *p, *s;
: >     ...
: >     for( p = s; *p; ++p )
: >         *p = toupper( *p );
:
: > Nearly as I can tell, dpANS says that loop ought to have been
:
: >     for( p = s; *p ++p )
: >         if( *p >= 0 )
: >             *p = toupper( *p );
:
: Gee, I always do this:
:
:       for(p = s; *p; p++)
:               if(islower(*p))
:                       *p = toupper(*p);
:
: While dpANS might have decided that toupper should bounds check, there
: are too many V7-oid compilers out there that it's better to put the
: bounds check in. Personally, I think that toupper should have been left
: the way it was. Everything else in stdio forces you to do your own bounds
: checking, so why should this be an exception?

There are two distinct issues:

    1) The signedness of a character.
    2) The range checking of islower/toupper.

If the character array may contain any character which is not
guaranteed to have a positive value, the *p may generate a negative
value. This will blow away many if not most islower's and toupper's.
This means that if that possibility exists, one must either use
unsigned characters or handle the negative values which may be
produced.

Once one has made sure that no negative values will make it into
toupper, one must also handle the case of toupper's that don't work
unless the character is a lower case letter. This means using
something like islower as well.

Combining the two code fragments above, the one with the sign test,
and the one with the islower test, will produce code that works for
all situations.

---
Bill
{ uunet!proxftl | novavax } !twwells!bill



More information about the Comp.lang.c mailing list