How do I transform an IF statement with 2 variables onto a switch function using C?

前端 未结 7 1900
伪装坚强ぢ
伪装坚强ぢ 2021-01-27 07:49

I have an IF-statement that I want to transform into a Switch-statement... But it has 2 variables! Is it possible to do it on C?

It is a rock, paper, scissors game:

7条回答
  •  生来不讨喜
    2021-01-27 08:09

    #include 
    
    #define SWITCH(a, b) char _a = a; char _b = b; if (0)
    #define CASE(a, b) } else if ((a == _a) && (b == _b)) {
    
    int main(void)
    {
        char play1, play2;
    
        printf("\nPlayer 1 - Enter your Play:");
        scanf ("%c", &play1);
        getchar();
        printf("\nPlayer 2 - Enter your Play:");
        scanf ("%c", &play2);
        getchar();
    
        SWITCH(play1, play2) {
            CASE('R','P') printf ("Paper wins!");
            CASE('R','S') printf ("Rock wins!");
            CASE('R','R') printf ("Draw!");
        }
        return 0;
    }
    

    It's a joke :P

    EDIT: case support of ":"

    #define PASTE(a, b) a##b
    #define LABEL(a, b) PASTE(a, b)
    #define SWITCH(a, b) char _a = a; char _b = b; if (0)
    #define CASE(a, b) } else if ((a == _a) && (b == _b)) { LABEL(LBL, __LINE__)
    

    But doesn't work with:

    CASE('R','R'): printf ("Draw a!"); CASE('S','R'): printf ("Draw!");
    

    Two cases in the same line

    Solved using:

    #define SWITCH(a, b) char _a = a; char _b = b; if (0)
    #define CASE(a, b) } else if ((a == _a) && (b == _b)) {switch(1) case 1
    

    Hope nobody use it :)

提交回复
热议问题