Character Classification with ctype.h in C
ctype.h classifies single characters as ints: isdigit, isalpha, isalnum, isspace, isupper/islower, ispunct, plus converters toupper/tolower. They replace hand-written range checks (c >= '0' && c <= '9') with locale-aware, self-documenting calls β the vocabulary of parsers, validators, and lexers.
Two rules: pass values representable as unsigned char or EOF (plain char arguments with negative values are undefined behavior β cast: isdigit((unsigned char)c)), and remember these are often macros evaluating arguments multiple times (no side effects inside).
Classify, don't compare ranges
isdigit(c), isalpha(c), isspace(c) β readable intent replacing brittle hand-rolled range tests.
Cast to unsigned char
isdigit((unsigned char)c) β negative char values are UB uncast; the cast is mandatory hygiene, not style.
Convert case safely
c = toupper((unsigned char)c); β locale-aware case mapping without arithmetic assumptions about alphabets.
No side effects inside
isdigit(*p++) may evaluate twice as a macro β advance pointers on separate lines.
#include <stdio.h>#include <ctype.h>Β int main(void) { char s[] = "aB3"; int digits = 0; for (int i = 0; s[i]; ++i) if (isdigit((unsigned char)s[i])) ++digits; printf("%d\n", digits); return 0;}Recommended resourcesAffiliate links Β· may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself β building beats watching.