Course contentsShow
← C
Lesson 106 of 1,2192. Variables and TypesFree lesson

Characters as small integers

Characters as small integers

What you'll learn: You will understand how C treats characters as small whole numbers behind the scenes using the ASCII standard.

The Secret Identity of 'A'

In C, a char is often used to store letters, but the computer doesn’t actually see the shape of the letter "A". Computers are essentially giant calculators that only understand numbers. To bridge this gap, C uses a system called ASCII (American Standard Code for Information Interchange).

Think of it like a secret decoder ring from a cereal box. Every character is assigned a specific number. When you type 'A', the computer stores the number 65. When you type 'a', it stores 97. Because a char is technically just a small 8-bit integer, you can actually perform math on letters.

Code: Mixing Letters and Numbers

Because a char is just a number, C allows you to print the same variable as either a symbol or a digit. You can even add 1 to a letter to get the next one in the alphabet.

#include <stdio.h>

int main() {
    char letter = 'A';

    // %c prints the character symbol, %d prints the integer value
    printf("As a character: %c\n", letter); // Output: A
    printf("As a number: %d\n", letter);    // Output: 65

    // Adding 1 to a character
    char nextLetter = letter + 1;
    printf("Next letter is: %c (which is %d)\n", nextLetter, nextLetter);
    
    return 0;
}

Why This Matters

This "dual identity" is incredibly powerful. If you want to convert a lowercase letter to uppercase, you don't need a complex dictionary. You simply subtract 32 from the lowercase value (because the distance between 'a' and 'A' in the ASCII table is always 32).

Similarly, if you have the character '5' and you want the actual integer 5 to do math, you can't just use it directly. The character '5' is actually the number 53 in ASCII. However, by understanding that characters are just numbers, you can easily translate between symbols and the values they represent.

Key takeaway

A char in C is just a small integer that the computer translates into a symbol using the ASCII table.