C and C++ character data type: unsigned char type and signed char type
Character data type is one of the built-in data types in C++.This type allows the programmer to use characters (the English alphabets,numbers and special characters) in their programs. The keyword of this data type is ‘char‘ and it has a size of 8 bits.If you want to use this data type simply write the keyword and declare a variable for it.
For various conveniences char type is also divided into three types:char ,signed char and unsigned char data type.
A simple program is given below which uses the char type and also it print out it’s size.
#include <iostream> using namespace std ; int main( ) { char c=’N’ , c1 ; //Note the single quotation c1=c ; cout<< c << ” , ” << c1 << endl ; cout << sizeof(c) ; cin.get() ; return 0 ; }
The output is
N N
1
Note to assign a character literal to a char variable a single quotation is used.And the size 1 above means 1 byte,so a char type occupy only one byte.Considering the size of the char type it is in fact one of the smallest -another is bool type- data type in C and C++.
Assigning integer and floating point value to char type variable
We can assign an integer or a floating point value to ‘char’ type,in this case how to know which character will be outputted for the integer of real value assigned? it is easy.
Suppose if we assign 45 to char type variable what will be the output.To know the output Look at the ASCII chart the link ASCII chart.The corresponding character of 45 is ‘-‘ so we will get ‘-‘ as the output.Consider the program today.
LInk :Integer data type
char c=45, c1=113 ; cout<< "c=" << c << endl << "c1=" << c1 ;
Output,
c=-
c1=q
If we had assigned 100 we would have gotten ‘d’ as the output.
Assigning floating point value also works the same way as assigning integer value to the char variable.Here if value with fraction is assigned to the char variable then the fraction part will be truncated and the corresponding character of the truncated value will be the output.And also if a character is assigned to floating point type variable the integer value of that character is the output.Look at the code below
char c=12.234 , c1=12 , c2=54.45 , c3=’M’ ; float f=c3 ; cout << c << “,” << c1 << “,” << c2 << “,” << f << endl ;
If you run the program c and c1 gives the same output and c2 gives ‘6’ and f gives 77 as the output.So,if float/real number is assigned to char variable it is treated as an integer and the fractional value-if found any-is removed.