(I know most people are going to say it's horrible).
I have written the following macros to easily write switchs using strings instead of if/else if/else :
#define str_switch( value ) \
do { \
const char * __strswitchptr__ = (value); \
if( 0 ) \
#define str_case( test ) \
} if( strcmp( __strswitchptr__, (test) ) == 0 ) { \
#define str_default \
} else { \
#define str_switchend \
} while( 0 ); \
Which i am using this way :
char * sVal = "D";
str_switch( sVal )
{
str_case( "A" )
printf( "Case A" );
break;
str_case( "B" )
printf( "Case B" );
break;
str_case( "C" )
printf( "Case C" );
break;
str_default
printf( "Error" );
}
str_switchend
But i can't figure out how i could modify it so i could use multiple cases :
char * sVal = "D";
str_switch( sVal )
{
str_case( "A" )
printf( "Case A" );
break;
str_case( "B" )
printf( "Case B" );
break;
str_case( "C" )
str_case( "D" )
str_case( "E" )
printf( "Case C" );
break;
str_default
printf( "Error" );
}
str_switchend
Any idea ? Thanks :-)
How about this?
When one case evaluates to true it will continue through all if's until a break is encountered:
#define str_switch( value ) \
do { \
const char * __strswitchptr__ = (value); \
int __previous_case_true = 0; \
if( 0 ) \
#define str_case( test ) \
} if( __previous_case_true \
|| strcmp( __strswitchptr__, (test) ) == 0 ) { \
__previous_case_true = 1; \
#define str_default \
} { \
#define str_switchend \
} while( 0 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With