Question

Convert char to int in C and C++

ccppgcc

Question

How can I convert a char to an int in C and C++?

In particular, I want to understand the difference between:

  • converting a character such as 'A' to its integer character code, and
  • converting a numeric character such as '7' to the integer value 7

Please explain how this works in both C and C++, and show the correct way to do it with examples.

Short Answer

By the end of this page, you will understand the two common meanings of converting a char to an int in C and C++:

  • getting the character's underlying integer code
  • turning a digit character like '5' into the number 5

You will also learn the correct syntax, how implicit conversion works, common mistakes to avoid, and where this appears in real programs.

Concept

In C and C++, a char is a small integer type used to store a character value. That means a char already has a numeric representation behind the scenes.

There are two different tasks people often mean when they say "convert char to int":

1. Get the character code

If you have a character like 'A', converting it to int gives its character code.

char ch = 'A';
int code = ch;

Here, code becomes the numeric value that represents 'A' in the execution character set. On most modern systems using ASCII-compatible encodings, 'A' is 65.

2. Convert a digit character to its numeric value

If you have '7' and want the number 7, you do not just assign it to int and expect 7.

char ch = '7';
int value = ch - '0';

This works because the digit characters '0' through '9' are stored in consecutive order. So if '7' has code 55 and '0' has code 48, then 55 - 48 = 7.

Why this matters

This comes up often when:

  • reading input one character at a time
  • parsing numbers from strings
  • validating user input
  • processing files or network data
  • implementing tokenizers, interpreters, or command parsers

Understanding the difference between character code conversion and digit parsing helps you write correct and reliable code.

Mental Model

Think of a char as a labelled card stored in a tiny numeric box.

  • The label might look like 'A' or '7'
  • But inside, the computer stores a number for that character

So there are two ways to "read" the box:

Reading the stored code directly

If the card says 'A', you can ask: "What number represents this character?"

That gives you the character code.

Interpreting a digit character as a number

If the card says '7', you can instead ask: "What number does this digit mean to a human?"

That gives you the numeric value 7.

A good analogy:

  • '7' as a character code is like the printed symbol on a keyboard key
  • 7 as an integer value is the quantity the symbol represents

They are related, but they are not the same thing.

Take Quiz

Syntax and Examples

Core syntax

Get the integer code of a character

C:

char ch = 'A';
int code = ch;

C++:

char ch = 'A';
int code = static_cast<int>(ch);

In C++, int code = ch; also works because the conversion is implicit, but static_cast<int>(ch) makes the intent explicit.

Convert a digit character to a number

char ch = '7';
int value = ch - '0';

Example 1: Character code

#include <stdio.h>

int main(void) {
    char ch = 'A';
    int code = ch;

    printf("Character: %c\n", ch);
    printf("Code: %d\n", code);

    return 0;
}

Possible output:

Character: A
Code: 65

Example 2: Digit character to integer

#include <stdio.h>

int main(void) {
    char ch = '7';
    int value = ch - '0';

    printf("Character: %c\n", ch);
    printf("Numeric value: %d\n", value);

    return 0;
}

Output:

Character: 7
Numeric value: 7

Example 3: Validate before converting

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

int main(void) {
    char ch = '8';

    if (isdigit((unsigned char)ch)) {
        int value = ch - '0';
        printf("Digit value: %d\n", value);
    } else {
        printf("Not a digit\n");
    }

    return 0;
}

This is safer because ch - '0' only makes sense for digit characters.

Step by Step Execution

Consider this example:

#include <stdio.h>

int main(void) {
    char ch = '5';
    int code = ch;
    int value = ch - '0';

    printf("%d\n", code);
    printf("%d\n", value);

    return 0;
}

Step by step:

  1. char ch = '5';

    • The variable ch stores the character '5'.
    • Internally, that character has a numeric code.
  2. int code = ch;

    • ch is promoted to int.
    • code becomes the character code for '5'.
    • On ASCII systems, this is 53.
  3. int value = ch - '0';

    • '0' is also a character with its own code.
    • On ASCII systems, '0' is 48.
    • So the calculation is effectively 53 - 48.
    • The result is 5.
  4. printf("%d\n", code);

    • Prints the code, usually 53.
  5. printf("%d\n", value);

    • Prints the numeric digit value, 5.

Typical output:

53
5

This example clearly shows the difference between:

  • the character's stored code
  • the digit's numeric meaning

Real World Use Cases

Parsing user input

If a user types a single digit, you may receive it as a char and need to turn it into an integer.

char ch = '3';
int number = ch - '0';

Reading structured text files

When processing CSV, logs, or custom text formats, programs often inspect one character at a time.

  • check whether a character is a digit
  • convert digits into numbers
  • build full integers from multiple characters

Simple calculators and interpreters

A calculator that reads 2+3 may scan characters and decide whether each one is:

  • a digit
  • an operator
  • whitespace

Digit characters often need conversion before math can be done.

Embedded systems and serial input

Microcontrollers often receive data as bytes or characters over serial connections. If the input is '4', the code may need to convert it to integer 4.

Validation logic

Programs often check whether a character is a valid digit before conversion.

if (ch >= '0' && ch <= '9') {
    int value = ch - '0';
}
Take Quiz

Real Codebase Usage

In real projects, developers usually do not convert characters in isolation. They combine this idea with validation, parsing, and error handling.

Guard clauses for invalid input

A common pattern is to reject non-digits early.

int digit_to_int(char ch) {
    if (ch < '0' || ch > '9') {
        return -1;
    }
    return ch - '0';
}

This keeps the function simple and protects against bad input.

Parsing multiple digits

Real programs often convert a whole string of digit characters into an integer.

int result = 0;
for (int i = 0; str[i] != '\0'; i++) {
    if (str[i] < '0' || str[i] > '9') {
        return -1;
    }
    result = result * 10 + (str[i] - '0');
}

Here, str[i] - '0' is the core building block.

Validation with library functions

Developers often use isdigit() from <ctype.h> in C or <cctype> in C++.

#include <ctype.h>

if (isdigit((unsigned char)ch)) {
    int value = ch - '0';
}

Explicit intent in C++

In C++ codebases, developers may prefer static_cast<int>(ch) when they want the code value, because it makes the conversion more obvious.

char ch = 'A';
int code = static_cast<int>(ch);

Error-handling patterns

In larger systems, instead of returning -1, code may:

  • return a boolean success flag
  • use an output parameter
  • throw an exception in C++
  • use std::optional<int> in modern C++

But the core digit conversion logic is still usually ch - '0'.

Common Mistakes

Mistake 1: Expecting '7' to become 7 automatically

Broken code:

char ch = '7';
int value = ch;

This gives the character code, not the numeric digit value.

Fix:

int value = ch - '0';

Mistake 2: Using ch - '0' on non-digit characters

Broken code:

char ch = 'A';
int value = ch - '0';

This compiles, but the result is not a meaningful digit conversion.

Fix:

if (ch >= '0' && ch <= '9') {
    int value = ch - '0';
}

Or use isdigit().

Mistake 3: Confusing characters with strings

Broken code:

char ch = "7";

"7" is a string literal, not a character literal.

Fix:

char ch = '7';

Use single quotes for a single character.

Mistake 4: Assuming all character values should be printed with %c

Broken code:

char ch = 'A';
printf("%c\n", (int)ch);

If you want the integer code, print it as an integer.

Fix:

printf("%d\n", (int)ch);

Mistake 5: Forgetting input validation

Broken code:

int value = ch - '0';

If ch comes from user input or a file, it may not be a digit.

Fix:

if (isdigit((unsigned char)ch)) {
    int value = ch - '0';
}

Mistake 6: Misusing signed character values

In some systems, char may be signed. This matters more when working with non-ASCII byte values or functions like isdigit().

Safer pattern:

if (isdigit((unsigned char)ch)) {
    int value = ch - '0';
}

Casting to unsigned char before calling isdigit() avoids undefined behavior for negative char values.

Comparisons

TaskExample inputCorrect approachResult
Get character code'A'int code = ch;Usually 65
Get numeric digit value'7'int value = ch - '0';7
Validate then convert'7'isdigit((unsigned char)ch) then ch - '0'Safe digit conversion
Convert full string number"123"Use parsing logic like strtol, atoi, or manual loop123

char to int code vs digit conversion

ConceptMeaningExample
Character code conversionGet the numeric code used to store the character'A' -> 65
Digit conversionInterpret a digit character as its numeric value'5' -> 5

C vs C++

LanguageCommon style
Cint code = ch; or (int)ch
C++int code = ch; or static_cast<int>(ch)

In both languages, the actual idea is the same. The main difference is that C++ often prefers static_cast<int>(ch) for readability and type safety.

Take Quiz

Cheat Sheet

Quick reference

Get the integer code of a character

C:

char ch = 'A';
int code = ch;

C++:

char ch = 'A';
int code = static_cast<int>(ch);

Convert a digit character to its numeric value

char ch = '8';
int value = ch - '0';

Validate first

if (ch >= '0' && ch <= '9') {
    int value = ch - '0';
}

Or:

#include <ctype.h>
if (isdigit((unsigned char)ch)) {
    int value = ch - '0';
}

Rules to remember

  • char is an integer type in C and C++.
  • int code = ch; gives the character code.
  • ch - '0' only makes sense for digit characters.
  • Use '7' for a character, not "7".
  • Validate input when the character may not be a digit.
  • In C++, static_cast<int>(ch) makes conversion intent clearer.

Common results on ASCII systems

CharacterCodeDigit value if applicable
'0'480
'5'535
'9'579
'A'65not a digit

Edge case

If you call isdigit(ch), prefer:

isdigit((unsigned char)ch)

This is safer when char may be signed.

FAQ

What is the difference between '7' and 7 in C and C++?

'7' is a character literal. 7 is an integer literal. The character '7' has a character code and is not the same as the numeric value 7.

How do I convert '9' to the integer 9?

Use:

int value = ch - '0';

This works when ch is a digit character from '0' to '9'.

How do I get the ASCII value of a character?

Assign the character to an int or cast it:

int code = ch;

On ASCII-compatible systems, this gives the ASCII code.

Does int x = 'A'; work in both C and C++?

Yes. In both languages, char can be promoted to int.

Why does char ch = '5'; int x = ch; give 53 instead of 5?

Because it gives the character code for '5', not the numeric meaning of the digit. Use ch - '0' to get 5.

Should I use atoi for a single character?

Usually no. atoi is for strings, not single char values. For one digit character, ch - '0' is simpler.

Is ch - '0' guaranteed to work?

It works for digit characters because the basic character set stores '0' through '9' in increasing consecutive order.

How do I safely check whether a character is a digit?

Use either:

ch >= '0' && ch <= '9'

or:

isdigit((unsigned char)ch)
Take Quiz

Mini Project

Description

Build a small program that reads a single character and tells the user both its character code and, if it is a digit, its numeric value. This demonstrates the difference between raw character-to-integer conversion and digit parsing, which is a very common source of confusion for beginners.

Goal

Create a program that accepts one character, prints its integer code, and conditionally converts it to a numeric value if it is a digit.

Requirements

  • Read one character from standard input.
  • Print the character's integer code.
  • Check whether the character is a digit.
  • If it is a digit, print its numeric value using ch - '0'.
  • If it is not a digit, print a clear message instead.
Take Quiz

Keep learning

Related questions

View more