Reputation: 275
I am new to MFC. I am trying to do simple mfc application and I'm getting confuse in some places. For example, SetWindowText
have two api, SetWindowTextA
, SetWindowTextW
one api takes char *
and another one accepts wchar_t *
.
What is the use of char *
and wchar_t *
?
Upvotes: 13
Views: 35312
Reputation: 355
SetWindowTextA
takes char*, which is a pointer to ANSI strings.
SetWindowTextW
takes wchar_t*, which is a pointer to "wide" strings (Unicode).
SetWindowText
has been defined (#define) to either of these in header Windows.h
based on the type of application you are building. If you are building a UNICODE build then your code will automatically use SetWindowTextW
.
SetWindowTextA
is there primarily to support legacy code, which needs to be built as SBCS (Single byte character set).
Upvotes: 1
Reputation: 116048
char
is used for so called ANSI family of functions (typically function name ends with A
), or more commonly known as using ASCII character set.
wchar_t
is used for new so called Unicode (or Wide) family of functions (typically function name ends with W
), which use UTF-16 character set. It is very similar to UCS-2, but not quite it. If character requires more than 2 bytes, it will be converted into 2 composite codepoints, and this can be very confusing.
If you want to convert one to another, it is not really simple task. You will need to use something like MultiByteToWideChar
, which requires knowing and providing code page for input ANSI string.
Upvotes: 28
Reputation: 5
char* : It means that this is a pointer to data of type char.
Example
// Regular char
char aChar = 'a';
// Pointer to char
char* aPointer = new char;
*aPointer = 'a';
// Pointer to an array of 10 chars
char* anArray = new char[ 10 ];
*anArray = 'a';
anArray[ 1 ] = 'b';
// Also a pointer to an array of 10
char[] anArray = new char[ 10 ];
*anArray = 'a';
anArray[ 1 ] = 'b';
wchar_t* : wchar_t is defined such that any locale's char encoding can be converted to a wchar_t representation where every wchar_t represents exactly one codepoint.
Upvotes: -4
Reputation: 213258
On Windows, APIs that take char *
use the current code page whereas wchar_t *
APIs use UTF-16. As a result, you should always use wchar_t
on Windows. A recommended way to do this is to:
// Be sure to define this BEFORE including <windows.h>
#define UNICODE 1
#include <windows.h>
When UNICODE
is defined, APIs like SetWindowText
will be aliased to SetWindowTextW
and can therefore be used safely. Without UNICODE
, SetWindowText
will be aliased to SetWindowTextA
and therefore cannot be used without first converting to the current code page.
However, there's no good reason to use wchar_t
when you are not calling Windows APIs, since its portable functionality is not useful, and its useful functionality is not portable (wchar_t
is UTF-16 only on Windows, on most other platforms it is UTF-32, what a total mess.)
Upvotes: 4