Saturday 4 April 2020

Character Data Type in C++


Character Data Type
The character type is used to store characters - typically ASCII characters but not always. For example:
charmenuSelection = 'q';
charuserInput = '3';
Note how a character is enclosed within single quotes. We can also assign numeric values to variables of character type:

charchNumber = 26;

We can declare signed and unsigned characters, where signed characters can have positive and negative values, and unsigned characters can only contain positive values.

signed char myChar = 100;
signed char newChar = -43;
unsigned char yourChar = 200;
Note that if we use a plain char, neither signed nor unsigned:

chardataValue = 27;

it may differ between compilers as to whether it behaves as a signed or unsigned character type. On some compilers it may accept positive and negative values, on others, it may only accept positive values. Refer to your compiler documentation to see which applies.
A char is guaranteed to be at least 8 bits in size. C++ also provides the data type wchar_t, a wide character type typically used for large character sets. An array of characters can be used to contain a C-style string in C++. For example:

charaString[] = "This is a C-style string";


Note that C++ also provides a string class that has advantages over the use of character arrays.

No comments:

Post a Comment