Character

What is Char Data Type?

The CHAR data type stores character data in a fixed-length field. Data can be a string of single-byte or multibyte letters, numbers, and other characters that are supported by the code set of your database locale.

For example,

char group = ‘B’;
To print a name or a full string, we need to define char array. 
 char group = 'B';
char name[30] = "Student1";
printf("group is %c, name is %s", group, name);

Note that for a single character, we use single quotes, but for String (character array), we use double-quotes. Since its an array, we have to specify the length (30 in this case).

Just like the int data type, char can be signed (range from -128 to +127) or unsigned (0 to 255). C stores the binary equivalent of the Unicode/ASCII value of any character that we type. In our above example, the char group will be stored as a value ‘066’.

You can think of char also as an int value, as char takes int values too. The importance of signed and unsigned comes when you store an int between the specified range in a char.

Here is an example to help understand signed and unsigned chars better –

signed char char1 = -127;
unsigned char char2 = -127;
printf("char1 is %d, char2 is %d", char1, char2);

Note that since we are taking in int values, we will print as %d and not %c. Since char1 is signed, the printf will give value as -127. However, char2 is unsigned, which means the range is from 0 to 255, -127 is out of range. So, it will print 129. Same way, if you assign char2 as -1, you will get a value of 255.

Share Button

Feedback is important to us.

Leave a Reply

Your email address will not be published. Required fields are marked *

error: Content is protected !!