Hi there,

I want to know about wchar_t data type i.e. how it is used and why we use it. And also what is the difference between char and wchar_t. One last thing why we write L before wchar_t initialization.

  #include <iostream.h>
   void main()
      wchar_t w;
      w = L'A';
      cout << "Wide character value::" << w << '\n';
      cout << "Size of the wide char is::" << sizeof(w);

When I output hello in wchar_t it shows 111. What is the logic behind this. Thanks !

3 Years
Discussion Span
Last Post by deceptikon

It is used just like normal char.

The only difference is between their size which is 4 bytes in case of wchar_t which is 1 byte in char data ype.
Wide characters are used mainly to represent non-English or exotic character sets.

Moreover in your code explicitly preceding string literal with 'L' is not required as w is already of type wchar_t.
'L' is used to explicitly make the string literal of wchar_t instead of char.


how it is used and why we use it

In theory you would use it just like char, and the purpose is to support extended character sets. The char type for character usage was really designed and intended for character sets (and language alphabets) that can fit into a single byte, such as ASCII or EBCDIC.

In practice, conforming to larger character sets such as Unicode means you're targeting internationalization as a goal, which is quite a bit more complex than just swapping char for wchar_t. Even when you stick to a single locale, conversion between char and wchar_t is often necessary.

And also what is the difference between char and wchar_t.

char is guaranteed to be a single byte. wchar_t is a typedef for one of the integer types, and it may be multiple bytes so that it can represent any value in a large character set. You can't assume any specific size for wchar_t.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.