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

Casting between char and int

Casting between char and int

What you'll learn: How to convert between characters and their numeric underlying values using explicit casting.

The Secret Identity of Characters

In C, a char isn't actually a letter; it’s a tiny integer in disguise. Every character on your keyboard is mapped to a specific number defined by the ASCII standard. For example, the uppercase letter 'A' is actually the number 65.

Because characters are just numbers, you can "force" C to treat a character like an integer (and vice versa) using explicit casting. This is like telling the compiler, "I know this looks like a letter, but I want you to treat it like its numeric ID for a moment."

How to Cast

To perform an explicit cast, you place the desired data type in parentheses immediately before the variable.

If you have a char and want to see its numeric code, you cast it to an int. If you have an int and want to see which character it represents, you cast it to a char. This is incredibly useful for math—for instance, if you want to shift a letter three places down the alphabet, you treat it as a number, add three, and turn it back into a letter.

Code Example

Think of the cast as a "translator" that changes the perspective of the data.

#include <stdio.h>

int main() {
    char letter = 'B';
    int code = 67;

    // Convert char to int to see the ASCII value
    int letterAsNumber = (int)letter; 
    
    // Convert int to char to see the symbol
    char numberAsLetter = (char)code;

    printf("The character %c has the ASCII code %d\n", letter, letterAsNumber);
    printf("The code %d represents the character %c\n", code, numberAsLetter);

    return 0;
}

Why Use It?

Explicit casting makes your intentions clear to anyone reading your code. While C sometimes performs this conversion automatically (implicit casting), writing (int)myChar tells the world that you are intentionally looking for the numeric "under-the-hood" value. It is commonly used when calculating offsets, such as converting a lowercase letter to uppercase or checking if a character falls within a certain numeric range.

Key takeaway

Use (int)myChar to find a character's numeric code, or (char)myInt to turn a number back into its symbolic character.