A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
isalnum returns nonzero if the character is a letter or a digit. It is equivalent to isalpha(c) || isdigit(c) but in a single call. Use it for validating identifiers, usernames, product codes, and any token that permits letters and numbers but rejects punctuation and whitespace. It is the most permissive of the common character class tests.
#include <stdio.h>#include <ctype.h>#include <string.h>int is_valid_username(const char *s) {if (strlen(s) == 0) return 0;for (const char *p = s; *p; p++) {if (!isalnum((unsigned char)*p) && *p != '_') {return 0;}}return 1;}int main(void) {const char *names[] = {"alex42", "user_name", "bad name", "hello!", "admin123"};int n = 5;for (int i = 0; i < n; i++) {printf("%-12s -> %s\n", names[i],is_valid_username(names[i]) ? "valid" : "INVALID");}return 0;}
The validator allows letters, digits, and underscores. The space in "bad name" fails isalnum and is not an underscore, so it is rejected. The exclamation mark in "hello!" fails for the same reason. This pattern appears in every input validation function that sanitizes user-supplied identifiers.
isalnum is the permissive gate. It lets letters and digits through and blocks everything else. Combine it with explicit exceptions (like underscore) for real-world validators. Next: ispunct, which tests for the characters isalnum rejects.
Finish the lesson once you have worked through the material. This awards ★ 10 XP.