Wide char in C++
Wide char in C++ is a data type like char, int, string, float, and more. Wide char is another data type that caters to character-type data. However, it is much different from the char data type.
Differences
The following table represents the differences between a char data type and a wide char data type:
Char | Wide Char |
Takes up one byte of memory | Takes up two or four bytes of memory. Depends on the compiler |
Can take upto 256 values | Can take upto 65536 values |
Corresponds to ASCII value | Corresponds to UNICODE value |
Syntax
We can use the wide char using the following syntax:
wchar_t <variable name> = L<char val>;
The
wchar_tkeyword is used to declare a variable of type wide char.The
Lprefix is used before the character data to inform the compiler that the following data is of type wide char.
Code example
Let's understand how wide char variables are used in a C++ program:
#include <iostream>using namespace std;int main() {wchar_t x = L'E';wcout << x << endl;//size of wide charwcout << sizeof(x);}
Code explanation
Line 5: We declare a wide char type and initialize with the value
'E'.Line 6: We use
wcoutto display the value of a wide char. Thewprefix is used before every char type function to make it work with wide char data types, for example,wcout,wcin, and more.Line 7: The
sizeof()function returns the size in bytes of the wide char variable.
Strings using wide char
We can also create strings with a wide char array:
#include <iostream>using namespace std;int main() {wchar_t wideCharArray[] = L"Educative";wcout<<wideCharArray;}
Just like a char array, wchar_t arrays can also store strings, and wcout can display this array as a string.
Free Resources