Is there a good example of how toupper() works?

Alvin "the Chipmunk" Sylvain asylvain at felix.UUCP
Fri Oct 26 07:42:09 AEST 1990


Ye gadz, recursive follow-ups!

In article <152580 at felix.UUCP> asylvain at felix.UUCP,
  I wrote:
> In article <11021 at hubcap.clemson.edu> svissag at hubcap.clemson.edu
> (Steve L Vissage II) writes:
> > From article <1990Oct17.170914.683 at wpi.WPI.EDU>, by profesor at wpi.WPI.EDU
> > (Matthew E Cross):
> > > Nope, won't work - the return value of 'toupper' is undefined if the input
> > > is not a lowercase character.
> >   
> > So define your own toupper() macro.  That's what I did.
> > #define toupper(ch) ((ch<123 && ch>96) ? ch-32 : ch)
> 
> Two points: first, your macro is *disgustingly unreadable* (and probably
> incorrect ...haven't checked).  This is better:
> 
> #define toupper(ch) (((ch) >= 'a' && (ch) <= 'z') ? (ch) + 'A' - 'a' : (ch))
> #define tolower(ch) (((ch) >= 'A' && (ch) <= 'Z') ? (ch) + 'a' - 'A' : (ch))

Upon re-reading this, I've decided that it's not *much* better from a
readability point of view.  Try this:

#define toupper(ch) (((ch) >= 'a' && (ch) <= 'z')      \
                                ?  (ch) + 'A' - 'a'     \
				:  (ch))

#define tolower(ch) (((ch) >= 'A' && (ch) <= 'Z')      \
                                ?  (ch) + 'a' - 'A'     \
				:  (ch))

Please note that spaces are deliberate.  This is also what is known as a
"dangerous" macro, in that if you pass it something like '*ch++', your
results may not be what you expect.  Therefore, following convention,
it ought to be TOUPPER and TOLOWER as warning.  I still maintain that
you should forget the whole thing and use the library functions.



More information about the Comp.lang.c mailing list