C Switch / case macros, several cases

(I know that most people are going to say this horribly).

I wrote the following macros to easily write switches 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 );                                                  \

I am using this method:

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 understand how I can change it, so I can use several 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: -)

+4
source share
2 answers

How about this? When one case evaluates to true, it will continue through everything, if until 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 );
+8
source

Instead, you can use the switch:

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++;
}
0
source

All Articles