Understanding Character Data Types in C: The Char Type
Learn about the char
data type in C, which is used to store a single character. Discover how to enclose characters in single quotes, such as 'A'
or 'c'
, and understand how to print characters using the %c
format specifier in the printf()
function.
C Character Data Types
The char
Type
The char
data type is used to store a single character in C. The character must be enclosed in single quotes, like 'A'
or 'c'
. To print a character, we use the %c
format specifier in the printf()
function.
Example: Storing and Printing a Character
Example
char myGrade = 'A';
printf("%c", myGrade);
Output
A
Using ASCII Values to Display Characters
If you are familiar with ASCII values, you can use them to display specific characters. In this case, you do not surround the ASCII values with single quotes, as they are numbers:
Example
char a = 65, b = 66, c = 67;
printf("%c", a);
printf("%c", b);
printf("%c", c);
Output
ABC
Tip: You can find a list of all ASCII values in our ASCII Table Reference.
Notes on Using the char
Type
Keep in mind that the char
type is used for storing single characters only. If you try to store more than one character in a char
variable, only the last character will be printed:
Example
char myText = 'Hello';
printf("%c", myText);
Output
o
Using Strings for Multiple Characters
To store multiple characters (or whole words), use strings instead of the char
type. For now, understand that strings are used for storing text, while the char
type is used for single characters:
Example
char myText[] = "Hello";
printf("%s", myText);
Output
Hello
In future chapters, you'll learn more about working with strings in C.