Characters

The third basic data type is char (from character). It holds one character: a letter, a digit, a punctuation mark or a space. You write the character in single quotes and print it with %c:

char size = 'M';
char row = 'F';
printf("Size: %c\n", size);
printf("Seat: %c%d\n", row, 12);

This prints:

Size: M
Seat: F12

A char is handy wherever one character is enough: a T-shirt size, a row in a cinema, a class (7B), or an answer, 'y' or 'n'.

Watch the quotes. Single quotes hold one character: 'M'. Double quotes hold text, even when it's only one letter long: "M". In C, text is something different from a character, and you'll work with it in the lesson on strings. If you try to store text in a char, the program doesn't compile:

#include <stdio.h>

int main(void) {
    char size = "M";
    printf("Size: %c\n", size);
    return 0;
}

The compiler reports:

main.c:4:10: error: incompatible pointer to integer conversion initializing 'char' with an expression of type 'char[2]' [-Wint-conversion]

The message looks scary, but it only says that the text "M" can't be stored in a char. One character goes in single quotes: 'M'.

Inside the computer, every character is stored as a number, its code. 'A' has the code 65, 'B' 66, and so on through the alphabet. Even a digit in quotes is a character with its own code: '7' is 55, not 7. You can see the code when you print a character with %d:

char letter = 'A';
printf("%c has the code %d\n", letter, letter);
printf("%c\n", letter + 1);

This prints:

A has the code 65
B

The same value prints as a character with %c and as its code with %d. And letter + 1 is 66, which is the code of B. This will come in handy when you work with text.

Now you know the three basic data types of C: int, double and char. C has a few more, for example for very large numbers, but this course doesn't need them. In the next lesson, you'll meet one more type, for true and false.

Instructions

Below, create a variable size of type char with the value 'M'.

On the next line, print it with %c:

Size: M

Below it, print the size once more as a character and as its code. Use one printf with %c and %d, and give size twice:

Code of M: 77

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

5/11