Page 88 - Programming Microcontrollers in C
P. 88

Pointers     73

                          The following function compares two strings. It returns a negative
                          number if the string p is less than the string q, 0 if the two strings
                          are equal, and a positive number if the string p is greater than the
                          string q.

                   int strcomp(char* p, char* q)
                   {
                       while( *p++ == *q++)
                       if(*(p-1) == ‘\0’) /* The strings are equal */
                       return 0; /* zero */
                       return *(p-1) - *(q-1); /* The strings are
                                             unequal, return the correct value*/
                   }
                              Here the while() statement will examine each character in the
                          string until the argument is not equal. Note, that the pointers p and q
                          are incremented after they are used. The test for equality will not
                          occur until after the pointers are incremented, so it is necessary to
                          decrement the pointer p to determine if the last equal value in the
                          two strings is a zero character. If the last value is a zero, the two
                          strings are equal, and a 0 is returned. If the last tested character is not
                          a zero, the two strings are not equal and the difference between the
                          last character in p and the last character in q is returned. This choice
                          will give the correct sign needed to meet the function specification.
                              Another approach can be used that eliminates the increments and
                          decrements within the program and confines them to the argument
                          of a for construct. Consider
                   int strcomp(char* p, char* q)
                   {
                       for( ; *p==*q ; p++, q++)
                          if( *p == ‘\0’)
                              return 0;
                       return *p - *q;
                   }

                              The pointers p and q are both incremented after the test in the
                          if statement. Therefore, the pointer values are correct for the if
                          statement as well as for calculation of the return value when the
                          strings are not equal.
   83   84   85   86   87   88   89   90   91   92   93