Archived

This topic is now archived and is closed to further replies.

kaiel090x

Nesting Switch...Case and if/else

Recommended Posts

Yes!

switch...case is generally discouraged where an if...else statement can go instead because it jumps rather ungracefully around your code (like goto, but not as bad). The only thing to remember about using case statements is to terminate cases with 'break;'. That way you can do anything that you would usually do in a function in a case statement, and it will execute up to the next break command. You can use this for effect, such as:


switch( myInt )
{
case 5:
cout << "5...\n";
case 4:
cout << "4...\n";
case 3:
cout << "3...\n";
case 2:
cout << "2...\n";
case 1:
cout << "1...\n";
default:
cout << "Liftoff!!!!\n";
break;
}


but it could be quite bad to forget 'break' if:


switch( myChoice )
{
case 1:
cout << "You chose 1!";
case 2:
cout << "You chose 2!";
break;
default:
cout << "Please enter a choice!";
}


Happy coding,
Gareth



EDIT: Forgive me if some of my syntax is up the spout, I haven't used switches for a couple of months!!!

Edited by - Obolus on August 11, 2001 2:47:51 PM

Share this post


Link to post
Share on other sites