Mood:
![](https://ly.lygo.net/af/d/blog/common/econ/bear.gif)
Topic: VC++
The Stringizer operator... # and Token pasting operator ##
A powerful preprocessor operator which you can use for surrounding your strings with quotes... and to combine your string tokens during compile time
I always use these operators for returning error constants as string...
For eg: If I have an error constant like ERROR_INVALID_EXP_DATE.
What should I do to return it as a string... Normally we will declare an LPCTSTR constant as follows...
static const LPCTSTR lpctszErrInvalidExpDate = _T( "ERROR_INVALID_EXP_DATE" );
Which becomes a hard chore if the error code to be returned is one two many, now the question how can we automate this...
A small macro can do the trick for us.
#define SWITCH_CASE_STRING( constVar )\
case constVar:\
{\
static LPCTSTR constVar##ReturnValue = _T( #constVar );\
return constVar##ReturnValue;\
}
LPCTSTR GetErrorString( const DWORD dwErrorCode_i )
{
SWITCH_CASE_STRING( SUCCESS )
SWITCH_CASE_STRING( ERROR_INVALID_EXP_DATE )
..etc
}// End GetErrorString
During compile time SWITCH_CASE_STRING expands to the following statements
case SUCCESS:
{
static LPCTSTR SUCCESSReturnValue = _T( "SUCCESS" );
return SUCCESSReturnValue;
}
That's it. Now you don't have to write up a case statement every time a new error is introduced...
Since the variables are static they won't be created unless the particular error occurs. And they won't be created every time since the variables are static.
Hope this helps you.