In C char is the data type that represents a single character. The char values are encoded with one byte code, by the ASCII table.
Let’s just create a char variable, give it a value and print it back to the console.
1 2 3 4 5 6 7 | int main() { char symbol = 'A'; printf("%c", symbol); printf("\n"); return 0; } |
We need to put the char literals(values) in single quotes. This way the compiler understands that this is a symbol and not a name of a variable.
As we said, in C char uses the ASCII code table. This means that the symbols have a specific order. For instance the symbol ‘A’ will always be just before ‘B’.
Also, the char values are represented by one byte code. For the computer it is just a number from 0 to 255.
These two mean that we can perform different arithmetic operations with the symbols. Most useful of them are compare and increment. We do these just like we do it with int variables. Here is the next example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | void compareChars(char symbol_1, char symbol_2) { if(symbol_1 < symbol_2) { printf("%c is before %c", symbol_1, symbol_2); } else if(symbol_1 > symbol_2) { printf("%c is before %c", symbol_2, symbol_1); } else { printf("The symbols are the same"); } } |
This function accepts two char arguments, compares them and then says what is their order.
Since we can increment and compare chars, we can do some interesting
tasks. For instance, we can create a loop that prints the alphabet. Also
we can print the symbols as numbers to get their ASCII codes.
1 2 3 4 5 6 7 8 | void printAlphabetCodes() { char letter; for(letter = 'A'; letter <= 'Z'; letter++) { printf("The code of %c is %d\n", letter, letter); } } |
I prepared a zip file that contains the source of the above examples. You can download and then run the examples on your computer: c-char.zip
The code is also available on Git Hub.
This is how the output of the example looks like:
There are some characters that we write in a special way. We call them escape sequences. When we write their values for a char literal(value) we use several characters to describe them. The first character is always the backslash \.
For instance, how would you save a single quote in a char variable? You cannot write char quote = ''';. This will give you an error. To save a single quote you need to use its escape sequence: \'.
This will be read by the compiler as one symbol. It will save only the single quote.
The same way we can save the symbol of the backslash. Its escape sequence is, you guessed it: '\\'.
Here are the most frequently used escape sequences:
In C char data type: