Cannot convert from 'const wchar_t *' to '_TCHAR *'
Asked Answered
A

5

7
_TCHAR* strGroupName = NULL;
const _TCHAR* strTempName = NULL;

//Assign some value to strTempName

strGroupName = _tcschr(strTempName, 92) //C2440

I get an error at the above line while compiling this code in VS2008. In VC6 it compiles fine.

Error C2440: '=' : cannot convert from 'const wchar_t *' to '_TCHAR *'

What seems to be the problem and how do I fix it?

Averment answered 16/6, 2009 at 5:37 Comment(0)
M
8

Try casting it as

strGroupName = (_TCHAR*)_tcschr(strTempName, 92);

Seems to me that VS2008 got a little more strict on type casts, and won't automatically do them in some cases.

Mesarch answered 16/6, 2009 at 5:40 Comment(0)
F
8
strGroupName = const_cast<_TCHAR*>( _tcschr(strTempName, 92));

This is because the variant of the function you're using has a const _TCHAR* as input and returns a const _TCHAR*.

Another variant would be to have strTempName declared as _TCHAR*, and not as const _TCHAR*. In this case, the variant function having a _TCHAR* parameter and returning a _TCHAR* value is used.

Freeload answered 16/6, 2009 at 6:17 Comment(3)
Is Jack's answer fine? It got rid of the compilation error but I want to know the difference between his and yours.Averment
This version is better: it allows you to be specific about what the cast is for, i.e. it's not casting from some unrelated type, it's just removing the const.Bombast
@Bobby Using const_cast operation will allow you to easy find the const casting in the code by performing a simple search. I don't recomment const casting unless is really necessary. The second alternative (make strTempName as non-const) is my preferred, because it implies no further constness changing. Btw, is any reason why you declared strTempName as const?Solanum
N
2

_tcschr is returning a const pointer. Hence the return value should be const _TCHAR* strGroupName = NULL; If it is not possible to change strGroupName to a const pointer then declare both the pointers as non-const pointers.

Nonsuit answered 16/6, 2009 at 5:45 Comment(3)
This is fine but I cannot change strGroupName to const because it will affect the rest of the code which does not expect a const variable. Functions for example.Averment
Then make strTempName & strGroupName both non-const.Nonsuit
+1 including the comment that both can be non-const (perhaps add it to the answer?)Bombast
B
2

strGroupName should also be a pointer to const.

const _TCHAR* strGroupName = _tcschr(strTempName, 92);

No need to declare it until the call to initialise it.

Bombast answered 16/6, 2009 at 9:18 Comment(0)
A
1

I got the same error when moving from C++14->20, was able to fix it by setting /Zc:StrictStrings- under CommandLine in my build properties.

Adanadana answered 15/8, 2023 at 13:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.