What is the difference between char and int in case of switch?

I recently started C ++, and studying the case of switching, I had this doubt.
What difference
int Fav_Car;
does it make if I use int or char in the following code: The switch enclosure code is as follows

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

When I ran the program, I noticed that using int returns me the default case and using char works fine. Why is this so? And also, what's the difference if I use case '1' :andcase "1" :

+4
source share
8 answers

switch(), '': 1, 1, '1', ASCII 1 ( , . ). ASCII 0x31 49 .

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

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

, , , , -, .


:
'1' ASCII ++, . - , '1' . , ( ). ASCII, ASCII .

+9

char int ?

char int, . , Fav_Car - case, case.

, char - [32, 127] (, char).

, "1": "1"

switch case (.. int, char). :

case '1':   // ok.

case "1":   // wrong because "1" is a string - not integral type.
+3

? char, int.

?

1 //int
'1' // char 1
"1" // string 1

int

int a;
switch(a){
    case 1 :
}
+2

, '1' - , 1.

'1' '1', ASCII- 49.

, :

char a = 1;
char b = '1';
int x  = a;
int y =  b;
cout << "a as int: " << x << "\n";
cout << "b as int: " << y;
+2

'1' - char, 1 - . , . .

+1

, INT ?

:

#include <iostream>

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

case '1' -

case "1" -

+1

ASCII i.e

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

, int 1, default, 1 .

1 != 49
1 != 50

, char '1', .

+1

: none; , switch. char int : . char 8 (0-255) int 32 ( -2 + 2 .).

Note that this charis a single character, not a string; and that you cannot use the string value in the instruction switchas you can in C #, Java and Swift, but switchcompiles to a hash table in memory for ultra-fast performance, that optimization cannot be performed with the current string types.

0
source

All Articles