Click here to Skip to main content
15,881,803 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi,

I have a Win32 library for which the character set is preset to - Use Unicode Character Set and I want to use a WCHAR array for storing a string literal constant.
For example:
WCHAR string[] = "MyWideCharString";


When I compile the code I get the error that states:
VB
Error   1   error C2440: 'initializing' : cannot convert from 'const char [17]' to 'WCHAR []'   14


I tried using _T macro also,but I got a compile error again:
VB
Error   1   error C3861: '_T': identifier not found 14


So how can I use the WCHAR character arrays in my library?
Posted

The problem is the syntax for a string literal. The type WCHAR is the character type wchar_t; the string literal for this type should be prefixed with "L":

C++
WCHAR string[] = L"MyWideCharString";


[EDIT]
You can also use portable declaration style:

C++
_TCHAR string[] = _T("MyWideCharString");


Here, _TCHAR and _T are just macro which works depending the definition of _UNICODE. They make type declaration either char or w_char and the string literal either L-prefixed or not, which allows you to switch from non-Unicode (ANSI) to Unicode version of the same code. This way, the type declarations and string literal using the macro remain consistent in either case.

See http://msdn.microsoft.com/en-us/library/dybsewaf(v=VS.100).aspx[^].

Null-terminated portable string types based on _TCHAR are LPTSTR and LPCTSTR, see
http://stackoverflow.com/questions/321413/lpcstr-lpctstr-and-lptstr[^].

—SA
 
Share this answer
 
v5
Comments
[no name] 27-May-11 2:18am    
Good one -SA
Can tell me how to send bug to microsoft.
for please see my prevous post.
Sergey Alexandrovich Kryukov 27-May-11 2:43am    
Thank you, Santosh,
I saw it, did not try to reproduce. I have no good idea about the situation with reporting to Microsoft. I've done it once too long time age, not sure Microsoft is really responsive.
--SA
ShilpiP 27-May-11 3:03am    
+5 :)
hakz.code 27-May-11 2:22am    
Hi SAKryukov,
Thanks for the reply,
I studied from this link - http://msdn.microsoft.com/en-uslibrary/ey142t48%28v=vs.80%29.aspx#_core_mfc_support_for_unicode_strings, that said to use _T macro for Unicode!so I assume in case of MFC to use _T and for win32 to use L.
Please correct if I am wrong.
Thanks
Niklas L 27-May-11 3:01am    
_T(x) is only a macro which will expand to prefix its argument string with 'L' if UNICODE is defined or just x otherwise. It can be used with or without MFC.
WCHAR string[] = TEXT("MyWideCharString");
 
Share this answer
 
Comments
Richard MacCutchan 6-Jan-13 12:22pm    
Why are you trying to answer a question that is nearly two years old?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900