Blog literacki, portal erotyczny - seks i humor nie z tej ziemi
Lesson 5: switch...case
I know that this is probably a let-down, after you learned all about functions, but
switch...case is important to know. After all, it can save space with if statements, and
it is useful. Besides, I couldn't think of anything else that I wanted to write about.
Switch...case looks like this:
switch(expression or variable)
{
case it equals this:
do this;
break;
case it equals this:
do this;
break;
case it equals this:
do this;
break;
...
default
do this
}
So, it works like this. The expression or variable has a value. The case says that if it
has the value of whatever is after this case then do whatever follows the colon. The break
says to break out of the case statements. Break is a keyword that breaks out of the
code-block, surrounded by braces, that it is in. So unless you want it to try the next
case then use break. --You can also use it to break out of loops, something that I failed
to mention at the time.--
What is it used for, the switch...case? Well, let's say that you are writing a menu
program, then you would want to process some input, right? Well, you would want to use a
switch...case statement to process more than one input, because it is more easily used than
if statements.
Here is an example program:
#include
#include
void main()
{
char input;
cout<<"1. Play game";
cout<<"2. Load game";
cout<<"3. Play multiplayer";
cout<<"4. Exit";
input=getch(); //Remember I said you don't need many functions...
switch(input)
{
case 1:
playgame();
break;
case 2:
loadgame();
break;
case 3: //Note use of : not ;
playmultiplayer();
break;
case 4:
break;
default:
cout<<"Error, bad input, quitting";
}
}
If you are not understand this, then try putting in if statements for the case statements.
Also, the reason exit works with a break is that after you break out of the switch
statement then it would be the end of the program. The same thing would be for default.
If you don't like that, then make a loop around the whole thing. I know I did not
prototype the functions, but it was a very simple example. You could easily make a few
small functions.
Note: My homepage is http://www.cprogramming.com. My email is lallain@concentric.net. Please
email me with comments and or suggestions. If you want to use this on your own site please
email me and add a link to http://www.cprogramming.com. Thanks :)