A char is a one-byte number. Which character each number means is fixed by a table: ASCII for the first 128 values. 'A' is 65, 'a' is 97, '0' is 48, a space is 32 and the newline '\n' is 10.
Letters are numbers
#include <stdio.h>
int main(void) {
char c = 'g';
printf("'%c' is %d\n", c, c);
printf("position in the alphabet: %d\n", c - 'a');
printf("uppercase: %c\n", c - 32);
char d = '7';
printf("digit value: %d\n", d - '0');
return 0;
}Because letters are in order, you can do arithmetic on them:
c - 'a'is a letter's position in the alphabet (0 fora);c - 32turns a lowercase ASCII letter into uppercase ('a' - 'A'is 32);d - '0'turns a digit character into its number:'7' - '0'is 7.
This is how toupper, atoi and the Caesar cipher work.
Beyond ASCII: Unicode and UTF-8
#include <stdio.h>
#include <string.h>
int main(void) {
char word[] = "অ";
printf("bytes: %zu\n", strlen(word));
for (int i = 0; word[i] != '\0'; i++) printf("%d ", (unsigned char)word[i]);
printf("\n");
return 0;
}ASCII has no Bangla letters, no accents and no emoji. Unicode gives every character in every script a number (a code point): অ is U+0985. UTF-8 stores those numbers in 1 to 4 bytes: ASCII characters keep their single byte, and others use 2, 3 or 4. So strlen counts bytes, not letters: "অ" has length 3. Watch the array in the visualizer: three bytes for one letter.
| Character | Code point | UTF-8 bytes |
|---|---|---|
A | U+0041 | 1 |
é | U+00E9 | 2 |
অ | U+0985 | 3 |
| 😀 | U+1F600 | 4 |
Quick check
Practice problems for this lesson
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.