Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#FFcccc
size_t count_preceding_whitespace(const char *s) {
  const char *t = s;
  size_t length = strlen(s) + 1;

  /* possibly *t < 0 */
  while (isspace(*t) && (t - s < length)) {
    ++t;
  }
  return t - s;
}

Compliant Solution (

...

Cast)

Pass character strings around explicitly using unsigned characters.

Code Block
bgColor#ccccff

size_t count_preceding_whitespace(const char *s) {
  const unsigned char *t = s;
  size_t length = strlen(s) + 1;

  while (isspace(*t) && (t - s < length)) {
    ++t;
  }
  return t - s;
}

Wiki Markup
This approach is inconvenient when you need to interwork with other functions that haven't been designed with this approach in mind, such as the string handling functions found in the standard library \[[Kettlewell 02|AA. C References#Kettlewell 02]\].

Compliant Solution (Cast)

This compliant solution uses a castThis compliant solution casts the character to unsigned char before passing it as an argument to the isspace() function.

Code Block
bgColor#ccccff
size_t count_preceding_whitespace(const char *s) {
  const char *t = s;
  size_t length = strlen(s) + 1;

  while (isspace((unsigned char)*t) && (t - s < length)) {
    ++t;
  }
  return t - s;
}

...