TIP: Click on subject to list as thread! ANSI
echo: c_echo
to: All
from: Rob Swindell
date: 2003-09-16 15:33:28
subject: Snippets ini.c

This file contains a function that demonstrates a common programming mistake
(hidden in the macro LAST_CHAR):

static char *StripTrailingSpaces(char *string)
{
      if (!string || (0 == strlen(string)))
            return NULL;

      while (isspace(LAST_CHAR(string)))
            LAST_CHAR(string) = NUL;

      return string;
}

from sniptype.h:

#define LAST_CHAR(s) (((char *)s)[strlen(s) - 1])

So this function (StripTrailingSpaces) calls strlen() twice for each trailing
space character in the string, and for those that don't know, strlen() has to
walk through the string character by character from the beginning looking for
the trailing nul-terminator. This is just a silly waste of CPU cycles and time.

Also, the initial check for a 0-length string performs yet-another strlen() on
the string in question. The strlen()-scan of the string is not necessary to
determine if it is 0-length or not. Simply checking the first element of the
array (or the first character pointed to) will suffice.

Here is a much faster and more efficient version of the function:

static char *StripTrailingSpaces(char *string)
{
        size_t len;

        if(string == NULL || *string == 0)
                return string; /* why would you return NULL if empty? */

        len = strlen(str);
        while(len && isspace(string[len-1])) 
                len--;

        if(string[len] != 0)
                string[len] = 0; /* Don't re-terminate, could be static str */
        
        return string;
}

-Rob

                                                  digital man

Snapple "Real Fact" #89:
The average American walks 18,000 steps a day.
--- SBBSecho 2.00-Win32
* Origin: Vertrauen - vert.synchro.net (1:103/705)
SEEN-BY: 633/267 270
@PATH: 103/705 218/903 10/3 106/2000 633/267

SOURCE: echomail via fidonet.ozzmosis.com

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.