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

前端 未结 8 1652
别跟我提以往
别跟我提以往 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:47

    Your misunderstanding has nothing to do with the switch() construct, it's all about the single quotes '': If you write 1, you get an integer of the value 1, when you put it in single quotes '1', you get the numeric value of the ASCII character for the digit 1 (this is a bit imprecise, see note below). That ASCII character has the numeric value of 0x31, or 49 in decimal. Now imagine the difference between

    switch( Fav_Car ) {
        case 1 :
            cout<< "That's cool";
            break;
        case 2 :
            cout<< "Even mine!";
            break;
        default :
            cout<< "Oh";
            break;
    }
    

    and

    switch( Fav_Car ) {
        case 49 :
            cout<< "That's cool";
            break;
        case 50 :
            cout<< "Even mine!";
            break;
        default :
            cout<< "Oh";
            break;
    }
    

    The second one is equivalent to the version that you posted, and I think it's clear why it behaves very differently from the first version.


    Note:
    While '1' yields an ASCII character value in most C++ implementations, that does not need to be the case. The implementation is free to use some other character code, so that the value of '1' is actually implementation defined. It could be virtually anything except zero (because that's used for the terminating null-byte in strings). However, most implementations do use ASCII encoding, which is why I assumed ASCII in the text above.

提交回复
热议问题