Summary: in this tutorial, you will learn what C character type is and how to declare, use and print character variables in C.
char type to store characters and letters. However, the
char type is integer type because underneath C stores integer numbers instead of characters.
In order to represent characters, the computer has to map each integer with a corresponding character using a numerical code. The most common numerical code is ASCII, which stands for American Standard Code for Information Interchange. The following table illustrates the ASCII code:
For example, the integer number
65 represents a character
A in upper case.
In C, the
char type has 1-byte unit of memory so it is more than enough to hold the ASCII codes. Besides ASCII code, there are various numerical codes available such as extended ASCII codes. Unfortunately, many character sets have more than 127 even 255 values. Therefore, to fulfill those needs, the Unicode was created to represent various available character sets. Unicode currently has over 40,000 characters.
Using C char type
In order to declare a variable with character type, you use the
char keyword followed by the variable name. The following example declares three
char key, flag;.
You can initialize a character variable with a character literal. A character literal contains one character that is surrounded with single quotation (
'). The following example declares
key character variable and initializes it with a character literal ‘
char key = 'A';
char type is the integer type, you can initialize or assign a
char variable an integer. However, it is not recommended since the code maybe not portable.
ch = 66;
Displaying C character type
To print characters in C, you use the
printf() function with
%c as a placeholder. If you use
%d, you will get an integer instead of a character. The following example demonstrates how to print character in C.
* File: main.c
* Author: zentut.com
* C Character type
char ch = 'A';
printf("ch = %c\n",ch);
printf("ch = %d, hence an integer\n",ch);
In this tutorial, you have learn about C character type and how to declare, use and print character variables in C.