understanding switch statements

Can someone help me out with switch statements, doesnt make sense to me
Hi, switch statement 'substituing' a if - else if - else if .... sequence.
for example, you have char variable witch some value, and you know, there is 'a', 'b', 'c' or 'd', so you can write:
1
2
3
4
5
6
7
8
char h;
/...
if (h == 'a')
   cout << "h is a";
else if (h == 'b')
   cout << "h is b";
else if (h == 'c')
//...and so on 


or you can simply use switch to select whitch way program should continue:
1
2
3
4
5
6
7
8
9
10
char h;
//...
switch (h)
{
case 'a':
   cout << "h is a"; break;
case 'b':
   cout << "h is b"; break;
case ..... 
}


switch statement making program a lot more synoptical

there are some things you should know:
every case label should end witch break;
you don't have to using {} between labels
1
2
3
4
5
6
7
8
switch (h)
{
case 'a':
   cout << "h is a";
   cout << "...";
   break;
//....
}


if you don't use break, program will continue in code below:
1
2
3
4
5
6
switch (h)
{
case 'a':
   cout << "h is a"; //now program will follow after next label
case 'b':
   cout << "In this moment h can be b, or a";


this can be used to couple more case labels into one code:
1
2
3
4
5
6
switch (h)
{
case 'a':
case 'b':
   cout << "h is a or b"; break;
}


and the last thing - default label
code in default label is done, when other labels cannot be done (that means when tested variable (in out example char h) is not equal to any label)
1
2
3
4
5
6
7
8
switch (h)
{
case 'a':
//....

default:
   cout << "I don't know what is h";
}


switch statement can be used with any numerical type (char, int, ...) but not witch text (char *).
thank you very much...im still new to programming :\
Hey CPlusPlusKing... i've been stuck on some c++ lingo in the past and cplusplus.com came through like a champ .. but i've gotten stuck on this switch case statement i went to http://en.wikipedia.org/wiki/Switch_statement

and that explained so much.. i know switch case very well now

Topic archived. No new replies allowed.