• Advertisement

Archived

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

Nesting Switch...Case and if/else

This topic is 6039 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Will code compile correctly if I nest an if statement inside of a case statement? ~ from the depths of the ocean

Share this post


Link to post
Share on other sites
Advertisement
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

  • Advertisement