Skip to main content
GameDev.net gamedev.net
🔒 Locked

Nesting Switch...Case and if/else

Started by kaiel090x Aug 11, 2001 at 1:18 PM 0 replies 550+ views
Original Post
kaiel090x
kaiel090x
Will code compile correctly if I nest an if statement inside of a case statement? ~ from the depths of the ocean
"He who fights monsters should look to it that he himself does not become a monster... when you gaze long into the abyss, the abyss also gazes into you."~Friedrich Nietzsche
Obolus
Obolus
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

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.