What's the difference between char and int in a switch case?

前端 未结 8 1646
别跟我提以往
别跟我提以往 2021-01-13 11:21

I started C++ recently and while learning switch case, I got this doubt.
What\'s the difference if I use int or char in the following code :
int Fav_Car;

相关标签:
8条回答
  • 2021-01-13 11:53

    Characters in switch cases are eventually converted to ASCII equivalent decimal i.e

    char '1' - int 49 
    char '2' - int 50
    

    For example, if input is integer int 1 , switch case will switch to default because 1 doesn't satisfy any case.

    1 != 49
    1 != 50
    

    However, in case input is character char '1', output will be the first case as your desire.

    0 讨论(0)
  • 2021-01-13 11:55

    Are you sure that INT is not working?

    The following code works well:

    #include <iostream>
    
    int main() {
        int fav_car = 2;
    switch(fav_car) {
            case 1 :
                std::cout<< "That's cool";
            break;
            case 2 :
                std::cout<< "Even mine!";
            break;
            default :
                std::cout<< "Oh";
            break;
        }
    }
    

    case '1' - it is a symbol

    case "1" - it is a string constant

    0 讨论(0)
提交回复
热议问题