CPP switch

Controlling Flow with switch Statement.

A swich statement has the form:

switch (expression)
    case valueOne: statement;
    case valueTwo: statement;
    case valueN:   statement;
    default:       statement;

Where :
  • Expression is any legal C++ expression that that returns an integer value.
  • Statements are any legal C++ statements or block of statements that is been evaluated.
  • If one of the case values matches the expression, program execution jumps to those statements and continues to the end of the switch block unless a break statement is encountered, which ends the switch block.
  • If nothing matches, execution branches to the optional default statement.
  • If no default and no matching case value exist, execution falls through the switch statement and the statement ends.
Source code Result
// Demonstrates switch statement
#include <iostream>
int main()
  using namespace  std;
  int number;
  cout << "Enter a number between 1 and 5: ";
  cin >> number;
  switch (number) {
  case 0: cout << "Too small number!";
  case 5: cout << "You select 5 " << endl;
    // fall through
  case 4: cout << "You select 5 or 4 " << endl;
  case 3: cout << "You select 3" << endl;
    // fall through
  case 2: cout << "You select 3 or 2" << endl;
   // fall through
  case 1: cout << "You select 3,2 or 1" << endl;
  default: cout << "Too large number" << endl;
  cout << endl << endl;
  return 0;
Enter a number between 1 and 5:3
You select 3
You select 3 or 2
You select 3,2 or 1

You can download this example here (needed tools can be found in the right menu on this page).

© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.