« February 2007 »
S M T W T F S
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28
You are not logged in. Log in

Programming Tips
Tuesday, 6 February 2007
Stringizer ( #) and Token pasting (## ) operator.
Mood:  hug me
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.


Posted by Nibu babu thomas at 5:09 PM
Updated: Monday, 26 February 2007 5:25 PM

View Latest Entries