Rhyous

December 5, 2009

What is the syntax for the switch and case statement in C++?

Filed under: C/C++ — J. Abram barneck @ 4:48 pm

The switch statement is often a good alternate for multiple if..else if...else statements.

switch (expression)
{
  case someConstantValue1 : 
    // Your code goes here...
    break;
 case  someConstantValue2: 
    // Your code goes here...
    break;
}

So lets look at this using an integer variable intValue and we will show you some other syntax capabilities.

switch (intValue) {

  case 1 : 
    // Your code goes here...
    break;

  case 2 : 
    // Your code goes here...
    break;

  case 3 : 
  case 4 : 
    // Both options 3 and 4 will run the same code
    // Your code goes here...
    break;

  case 10 : 
  case 5 : 
    // The options don't have to be in order but you may want to keep them order because you can.
    // Your code goes here...
    break;

  default : 
    // Anything that doesn't match will run this code.
    // Your code goes here...
    break;
}

Keywords: C++ switch case break syntax

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: