C Character Type

Summary: in this tutorial, you will learn what C character type is and how to declare, use and print character variables in C.

C Character Type

C uses char type to store characters and letters. However, the char type is integer type because underneath C stores integer numbers instead of characters.

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:

ASCII code Table

For example, the integer number 65represents a character A in upper case.

In C, the char type has a 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, 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 charvariables.

char ch; char key, flag;.
Code language: C++ (cpp)

In this example, we initialize a character variable with a character literal. A character literal contains one character that is surrounded by a single quotation ( ').

The following example declares key character variable and initializes it with a character literal ‘A‘:

char key = 'A';
Code language: C++ (cpp)

Because the char type is the integer type, you can initialize or assign a charvariable an integer. However, it is not recommended since the code may not be portable.

ch = 66;
Code language: C++ (cpp)

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 characters in C.

#include <stdio.h> int main() { char ch = 'A'; printf("ch = %c\n",ch); printf("ch = %d, hence an integer\n",ch); return 0; }
Code language: C++ (cpp)

In this tutorial, you have learned about C character type and how to declare, use and print character variables in C.

Was this tutorial helpful ?