C/C++ Arena

Step 5 of 6

Characters with char

A char holds a single character, such as a letter, digit or symbol. Character values are written in single quotes: 'A', '7', '?'. Double quotes mean something different: "A" is a string (text that can have many characters), which you'll meet properly later.

Print a char with %c:

#include <stdio.h>

int main(void) {
    char grade = 'B';
    char next = grade + 1;
    printf("Grade: %c\n", grade);
    printf("Next: %c\n", next);
    printf("As a number: %d\n", grade);
    return 0;
}
Grade: B
Next: C
As a number: 66

Characters are numbers

Computers only store numbers, so every character has a numeric code. The standard table is called ASCII: 'A' is 65, 'B' is 66, 'a' is 97, '0' is 48, and a space is 32. A char is really a small integer (one byte), and C lets you do arithmetic on it, which is why grade + 1 gives 'C'.

What you see depends on how you print it: %c shows the character, %d shows its code. It's the same value either way.

Common mistakes

Your turn: write a program that stores the letter T in a char named team, then prints two lines:

Team: T
Code: 84

Previous: Decimals with double Next: Constants and sizeof