C++ - char vs. wchar_t

char and wchar_t are character data types in C++.


  • char (character)
    • char is an 8-bit character data type.
    • char is for ANSI text.
    • CHAR is a typedef for char.
    • char* is used with Win32 ANSI ('A') functions. E.g. MessageBoxA().
  • wchar_t (wide character)
    • wchar_t is a 16-bit character data type.
    • wchar_t is for Unicode text. Specifically UTF-16.
    • WCHAR is a typedef for wchar_t.
    • wchar_t* is used with Win32 WIDE ('W') functions. E.g. MessageBoxW().

Almost every Windows API function has 2 versions. One that expects ANSI characters and strings, and one that expects WIDE characters and strings.

The MessageBox function. Ansi and Wide.


  #include <windows.h>
 
  MessageBoxA(HWND hWnd, const char* text, const char* caption, UINT uType);
 
  MessageBoxW(HWND hWnd, const wchar_t* text, const wchar_t* caption, UINT uType);
  

sizeof(char)==1. sizeof(wchar_t)==2. Don't forget the terminating null character which is a 1-byte char, or a 2-byte wchar.

sizeof(char) vs. sizeof(wchar_t)


  #include <string>
  #include <tchar.h>
  
  // ansi
  char message_a[] = "hello";
  auto len_a = strlen(message_a); // len = 5 chars
  auto size_a = sizeof(message_a); // size = 6 bytes (includes terminating null character)
  
  // wide
  wchar_t message_w[] = L"hello";
  auto len_w = wcslen(message_w); // len = 5 chars
  auto size_w = sizeof(message_w); // size = 12 bytes (includes terminating null character)
  

CHAR and WCHAR are typedefs for char and wchar_t.

Winnt.h


  // typedef declaration synonym
  typedef char CHAR;
  typedef wchar_t WCHAR;
  

Ads by Google


Ask a question, send a comment, or report a problem - click here to contact me.

© Richard McGrath