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;
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.