How to check a character value in C

By

Tagged: C

Learn how to check a character value in C using the ctype.h functions like isalpha(), isdigit(), isspace(), islower(), and isupper() to test a char.

When working in C, we can use the ctype.h standard library set of functions to check the value of a char type variable. You include the header, call the function you need, and it tells you if the character is a letter, a digit, whitespace, and so on.

We have access to several useful checks:

How to use them

Each function takes the character and returns a nonzero value when the check passes, and 0 when it fails. That makes them perfect inside an if:

#include <stdio.h>
#include <ctype.h>

int main(void) {
  char c = 'a';

  if (isalpha(c)) {
    printf("%c is a letter\n", c);
  }

  if (islower(c)) {
    printf("%c is lowercase\n", c);
  }

  return 0;
}

Running this prints:

a is a letter
a is lowercase

Notice that “nonzero” does not mean 1. Never compare the result to 1 directly, write if (isalpha(c)) instead of if (isalpha(c) == 1).

A common use case is validating user input. Here we check if a character is a digit before converting it to a number:

#include <stdio.h>
#include <ctype.h>

int main(void) {
  char c = '7';

  if (isdigit(c)) {
    int n = c - '0';
    printf("the digit is %d\n", n);
  }

  return 0;
}

This prints the digit is 7. Subtracting '0' works because digit characters are consecutive in the ASCII table.

What counts as whitespace?

I mentioned that isspace() checks if a character is a whitespace character. What is a whitespace character?

One thing to be careful with

These functions take an int, and the value must be representable as an unsigned char (or be EOF). Passing a negative value is undefined behavior.

This bites you when a plain char holds a byte outside the ASCII range, like accented characters, because on many platforms char is signed. The fix is a cast before the call:

if (isalpha((unsigned char)c)) {
  //...
}

For plain ASCII input you won’t notice the difference, but the cast makes the code correct for any byte.

Want me to talk about your product? You can sponsor this site.

Related posts about clang: