C++ char Data Type – All You Need To Know To Get Started!

Filed Under: C++
C Character Data Type

Hey, folks! In this article, we will be focusing on C++ char data type in detail.

C++ consists of various primitive and user-defined datatypes. Today, we’ll be understanding about character data type (char).

So, let us begin!!


What is char data type in C++?

Character data type in C++, enables us to store character type values in it. By, character type values, we mean, all the values enclosed into single quotes such as ‘x’, ‘1’, ‘@’, etc.

The char data type holds a memory space of 1 Byte i.e. 8 bits into it and can store one character at a time. Moreover, the memory space ranges from 0 to 255, respectively.

Let us now focus on the syntax of character data type in the upcoming section.


Declaration and Initialization of a char type variable

Have a look at the below syntax to declare a char type variable!

char variable = 'value';

Any value enclosed within the single quotes is treated as a char type value.


Examples of C++ char data type

In this example, we have declared a variable of type character and displayed it using C++ cout statement.

Example:

#include <iostream>
using namespace std;

int main() 
{

char var = 'P';

cout<<"The value of the character variable: "<<var<<endl;

return 0;
}

Output:

The value of the character variable: P

Let us now try to print escape sequences through character type as shown below–

Example:

#include <iostream>
using namespace std;

int main() 
{
char num1 = '1';
char var = '\t'; // escape sequence for tab space
char num2 = '2';
cout<<num1;

cout<<var;

cout<<num2;
return 0;
}

As seen below, the escape sequences get executed in the default mode even if they are enclosed in single quotes as character types.

Output:

1	2

Note: If we enclose the values in double-quotes, they will be treated as Strings. Thus, all the values need to be enclosed in single quotes in order to be considered as character type values.


Conclusion

By this, we have come to the end of this topic. Hope this article helps you to understand the concept well!

Feel free to comment below, in case you come across any question.

Stay tuned and do visit C++ programming with JournalDev for more such interesting posts being simplified here! 馃檪

Till then, Happy Learning!!


References

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages