(我知道大多数人会说这太可怕了。)
我编写了以下宏来轻松地使用字符串来编写开关而不是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 ); \
我正在使用这种方式:
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
但我无法弄清楚如何修改它以便我可以使用多种情况:
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
有什么想法吗?谢谢: - )
答案 0 :(得分:8)
这个怎么样?
当一个案例评估为真时,它将继续通过所有if,直到遇到break
:
#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 );
答案 1 :(得分:0)
您可以改用开关:
char * sVal = "D";
while ( *sVal ) {
switch ( *sVal ) {
case 'A':
printf( "Case A" );
break;
case 'B':
printf( "Case B" );
break;
case 'C':
case 'D':
case 'E':
printf( "Case C" );
break;
default:
printf( "Error" );
}
sVal++;
}