Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

switch statement in C++

In C++ programming, a Switch statement is a type of selection control mechanism used to select one choice when multiple choices are given. It can be used as an alternative of if else if structure.
Switch statements function somewhat similar to the if statement usually used for option menu selections. The switch structure contains only one expression at its beginning and multiple cases within its body. Each case consists of a statement or set of statements.
In C++, the general syntax of switch statement:

switch (expression)

   {

      case label-1:

            set of statements-1;

            break;

      case label-2:

            set of statements-2;

            break;

      case label-3:

            set of statements-3;

            break;

      ----    ---------------

      ----    ---------------

      default:

            set of statements-n;

   }



In the above syntax:
switchIt is a keyword that indicates the beginning of "switch" structure.
expression It is an expression that may be a single variable (or an arithmetic expression). Its returned value should be an integer or a single character.
case It is a keyword that is used in switch statement to match the value according to the given expression.
label-1 ..... label-3 They represents the labels for the each case. Every label must be unique, numeric constant or character constant value. The value returned by expression must be same as the data type of case labels
default It is a keyword that is used in switch structure to execute the statement ("set of statements-n;") as default if the value returned by the expression doesn't match with any case label.

 The 'default' keyword can be placed at any position in the switch structure. For example, it can be placed at the beginning of switch structure. Its use is optional.

 The value returned by the expression must not be a double or float value (or any other types of data).

Flowchart of switch statement

The flowchart of c++ switch structure is as follows:




This post first appeared on Programming Explain, please read the originial post: here

Share the post

switch statement in C++

×

Subscribe to Programming Explain

Get updates delivered right to your inbox!

Thank you for your subscription

×