Switch Statement in C++

Switch statement is an alternative of if else statement. Switch statement use arithmatic expression/constant rather than relational expression. The given expression evaluate and give some value, then this resultant value matched with given cases.

Syntax

Syntax of switch statement is as given.

switch ( expression / constant / variable ) {

     case constant-1 :

        statements;

     break;

     case constant-2 :

        statements;

     break;

     case constant-n :

        statements;

     break;

     default :

        statements;

}

switch

switch is keyword that specifies the beginning of switch statement. It is always written in lower case letters.

expression / constant / variable

Here one of the expression or constant value can be used.

1. Expression

Expression is the arithmatic expression that returns any numeric value.

2. Constant

Constant may be any numeric, character or string literal.

3. Variable

This may be any declared valid varibale name.

case constant-1:

case is the keyword that uses any constant literals which will match from the result of given expression. A switch statement may have multiple case statements. Colon ( : ) is used afte constant value. There is no need to use curly parentheses to specify more than one statements for single case block. Each statement within case block must end with semicolon.

break;

break is keyword that indicate ending of case block. Each case block must have a break statement. Semicolon is used after break statement.

default:

default is keyword that will execute statement when all case block goes flase to execute. It is good practice that switch statement must have a default block.

Example

#include <iostream>
using namespace std;

int main(int argc, char** argv) {
	int a = 1;
	// This switch statement uses variable
	switch (a) {
		case 1:
			cout<<"One";
		break;
		case 2:
			cout<<"Two";
		break;
		default:
			cout<<"Default";
	}
	return 0;
}

Output of Switch Example

switch statement in C++

Comments
Login to TRACK of Comments.