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

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

[sourcecode language=”cpp”]
switch (expression)
{
case someConstantValue1 :
// Your code goes here…
break;
case someConstantValue2:
// Your code goes here…
break;
}
[/sourcecode]

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

[sourcecode language=”cpp”]
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;
}
[/sourcecode]

Keywords: C++ switch case break syntax

Leave a Reply

How to post code in comments?

*