I have a TCHAR
array in my C++ code which I want to assign static strings to it.
I set an initial string to it via
TCHAR myVariable[260] = TEXT("initial value");
Everything works fine on this. However, when I split it in two lines as in
TCHAR myVariable[260];
myVariable = TEXT("initial value");
it bugs and gives a compiler error:
error C2440: '=': cannot convert from 'const char [14]' to 'TCHAR [260]'
shouldn't the TEXT()
function do exactly what I want here? convert the given string to TCHAR
s? Why does it work, when putting the two lines together? What do I have to change in order to get it working?
Some other confusing thing I have encountered:
I've searched the internet for it and have seen that there are also _T()
and _TEXT()
and __T()
and __TEXT()
. What are they for? Which of them should I use in what environment?
The macro _UNICODE is defined when you set Character Set to "Use Unicode Character Set", and therefore TCHAR would mean wchar_t . When Character Set if set to "Use Multi-Byte Character Set", TCHAR would mean char .
So depending on your compilation configuration, you can convert TCHAR* to string or wstring. To use UNICODE character set, click Project->Properties->Configuration Properties->General->Character Set, and then select "Use Unicode Character Set".
The reason the assignment doesn't work has very little to do with TCHAR
s and _T
. The following won't work either.
char var[260];
var = "str"; // fails
The reason is that in C and C++ you can't assign arrays directly. Instead, you have to copy the elements one by one (using, for example, strcpy
, or in your case _tcscpy
).
strcpy(var, "str");
Regarding the second part of your question, TEXT
, _T
and the others are macros, that in Unicode builds turn a string literal to a wide-string literal. In non-Unicode builds they do nothing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With