Course contentsShow
← C
Lesson 844 of 1,21912. The Standard LibraryFree lesson

Case testing with `isupper` and `islower`

Case testing with isupper and islower

What you'll learn: How to determine if a character is an uppercase or lowercase letter using built-in C functions.

The Case Detective

Imagine you are building a password validator or a text processor. You often need to know if a character is a "capital" letter or a "small" letter. While you could check this by comparing ASCII values manually (like checking if a character is between 'A' and 'Z'), C provides a much safer and more readable way to do this via the <ctype.h> library.

The functions isupper() and islower() act like digital detectives. You hand them a single character, and they return a "true" value (a non-zero integer) if the character matches the case you are looking for, or "false" (zero) if it does not.

How to use them

To use these functions, you must include the header file #include <ctype.h>.

It is important to remember that these functions are specific. isupper() only returns true for characters 'A' through 'Z'. If you pass it a lowercase 'a', a number '5', or a punctuation mark like '!', it will return false. Similarly, islower() only cares about 'a' through 'z'.

Example Code

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

int main() {
    char myLetter = 'B';
    char mySmallLetter = 'g';
    char mySymbol = '#';

    // Checking for uppercase
    if (isupper(myLetter)) {
        printf("'B' is an uppercase letter.\n");
    }

    // Checking for lowercase
    if (islower(mySmallLetter)) {
        printf("'g' is a lowercase letter.\n");
    }

    // Testing a symbol
    if (isupper(mySymbol) || islower(mySymbol)) {
        printf("This will not print because '#' has no case.\n");
    }

    return 0;
}

Why use these instead of manual checks?

You might be tempted to write if (c >= 'A' && c <= 'Z'). While this works for English, C's <ctype.h> functions are designed to be more robust. They make your intent clear to anyone reading your code: you aren't just doing math with characters; you are specifically asking about the "casing" of a letter. This leads to cleaner, more professional code that is easier to maintain.

Key takeaway

Use isupper(c) to check for capital letters and islower(c) to check for small letters, ensuring you #include <ctype.h> first.