views:

861

answers:

4
_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?

+1  A: 

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.

Jack B Nimble
+1. This got rid of the compilation error.
Bobby Alexander
Use const_cast.
GMan
+1  A: 

_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.

Naveen
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.
Bobby Alexander
Naveen
+1 including the comment that both can be non-const (perhaps add it to the answer?)
James Hopkin
+2  A: 
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.

Cătălin Pitiș
Is Jack's answer fine? It got rid of the compilation error but I want to know the difference between his and yours.
Bobby Alexander
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.
James Hopkin
@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?
Cătălin Pitiș
A: 

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.

James Hopkin