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

Bruce Worden bruce at seismo.gps.caltech.edu
Wed Oct 17 08:10:35 AEST 1990


In article poser at csli.stanford.edu (Bill Poser) writes:
>In article edh at ux.acs.umn.edu (Eric D. Hendrickson) writes:
>[believes that there is a problem with toupper and gives code including
>the following]
>>
>>	char *duh = "Hello";
>>	printf("%s\n", duh);
>>	while (*duh <= strlen(duh)) {
>>		if (islower(*duh)) *duh = toupper(*duh);
>>		*duh++;
>>	}
>The problem here is in the while termination condition. [ .... ]
>[ ... ] so the code in the loop is never executed.
>(An aside: since strlen(duh) never changes, either you or the compiler
>should move it outside the loop.) 

On the contrary, if this loop actually executed, the value of `strlen(duh)' 
would change at every iteration because `duh' is incremented in the loop.  
Similarly, in the final statement (deleted above):

	printf("%s\n",duh);

`duh' would point off the end of the string if the loop actually executed.  
I sent the original poster this code with an explanation, which people may 
comment on as they see fit:

#include <ctype.h>
main() {
        char *duh = "Hello";
        int i, limit = strlen(duh);
        printf("%s\n", duh);
        for(i=0; i<limit; i++) {
                if (islower(duh[i])) duh[i] = toupper(duh[i]);
        }        
        printf("%s\n", duh);
}

P.S.  Why did I rewrite the `while' loop above as a `for' loop?  I have 
found `for' loops to be very efficient (if that is a consideration) and, 
as I have said here before, I find subscripted arrays to be clearer and 
less error prone than incremented pointers (plus, vectorizing compilers 
love finding those iteration variables.)  (Having said that, I hope nobody 
finds a bug in my loop.)
--------------------------------------------------------------------------
C. Bruce Worden                            bruce at seismo.gps.caltech.edu
252-21 Seismological Laboratory, Caltech, Pasadena, CA 91125



More information about the Comp.lang.c mailing list