1

I am trying to create a TCHAR* variable by using

TCHAR* example = TEXT("example");

but it wont even compile and says: A value of type const wchar_t* cannot be used to initialize an entity of type TCHAR*. What should I do?

M.M
  • 138,810
  • 21
  • 208
  • 365
Mary
  • 63
  • 4
  • consider just using `auto example = L"example";` unless you really need to support non-unicode Windows 95 installations – M.M May 17 '20 at 20:23
  • Unless you are supporting Windows 98, **STOP USING TCHAR** and just go all in with wide-string APIs on Windows. Previous answers on this topic [here](https://stackoverflow.com/a/33712101/104458) and [here](https://stackoverflow.com/a/50572941/104458) and [here](https://stackoverflow.com/a/56307155/104458) and [here](https://stackoverflow.com/a/5527812/104458) – selbie May 18 '20 at 02:13
  • Even if you are supporting Win9x, there's the [Microsoft Layer for Unicode](https://en.wikipedia.org/wiki/Microsoft_Layer_for_Unicode). There's really *no* reason to avoid subscribing to the Unicode versions of the APIs today. – IInspectable May 18 '20 at 10:27
  • Or you could use the statement like:`TCHAR example[] = TEXT("example");` This will get a (7+1) size of `TCHAR` array and can be converted to `TCHAR *`(but must pay attention to the problem of array out of bounds). – Drake Wu May 27 '20 at 07:58
  • Hi, @Mary, If there is an answer available to you, feel free to [accept](https://stackoverflow.com/help/accepted-answer) it or you could add your own answer and [accept yourself](https://stackoverflow.blog/2009/01/06/accept-your-own-answers/). – Drake Wu May 27 '20 at 08:02

1 Answers1

4

You have to add const, because the TEXT() macro returns a pointer to a const wchar_t.

const TCHAR* example = TEXT("example");

If the assignment were allowed without the const, you would be able to modify the const wchar_t data through the pointer.

See also A value of type "const char*" cannot be used to initialize an entity of type "char *"

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Carlos A. Ibarra
  • 6,002
  • 1
  • 28
  • 38
  • 1
    Note that macros don't return objects of any type. TEXT simply adds the wide string literal prefix conditionally. The string literal itself is const whether the macro is used or not. – eerorika May 17 '20 at 14:04
  • 1
    Note, you can also use `LPCTSTR` instead of `const TCHAR*` directly: `LPCTSTR example = TEXT("example");` – Remy Lebeau May 18 '20 at 00:47