views:

38

answers:

1

When to use _TCHAR char types? _T(_TEXT) and L macros? What is the difference between them?

+3  A: 

The TCHAR type, the TEXT and _T macros are meant for code that compiles as both unicode and non-unicode builds.

  • If you configure your project as unicode, TCHAR is a typedef to wchar_t, otherwise it is just char.
  • The L in front of a string literal (e.g. L"Test") instructs the compiler that the constant is meant to be a unicode string.
  • The TEXT and _T macros both do insert this L in front of the literal if the project is build as unicode. TEXT("Test") is L"Test" in unicode builds, otherwise just "Test".

When calling library functions such as win32 API calls or the C runtime library, you always have to call the character-type-agnostic version of a function call, e.g. _tcslen instead of strlen or wcslen.

Examples:

// Non-unicode build
const char* str = "Hello, World";
size_t len = strlen( str );

// Unicode build
const wchar_t* str = L"Hello, World";
size_t len = wcslen( str );

// Works with both
const TCHAR* str = _T("Hello, World");
size_t len = _tcslen( str );
Timbo