blogger Indonesia

Follow judhyns blog

THE switch STATEMENT

Introduction

You can use a switch statement when you want to check multiple conditions. It can also be done using an if statement but it will be too lengthy and difficult to debug.

Program/Example

The general format for a switch statement is

switch (expressions) { case constant expressions } 

Example of a case constant expression and column:

switch (i/10) {     case 0: printf ("Number less than 10");    // A                 break;     case 1: printf ("Number less than 20");     // B                 break;     case 2: printf ("Number less than 30");    // C                 break;     default: printf ("Number greater than or equal to 40");    // D                 break; } 

Explanation

  1. The switch expression should be an integer expression and, when evaluated, it must have an integer value.

  2. The case constant expression must represent a particular integer value and no two case expressions should have the same value.

  3. The value of the switch expression is compared with the case constant expression in the order specified, that is, from the top down.

  4. The execution begins from the case where the switch expression is matched and it flows downward.

  5. In the absence of a break statement, all statements that are followed by matched cases are executed. So, if you don't include a break statement and the number is 5, then all the statements A, B, C, and D are executed.

  6. If there is no matched case then the default is executed. You can have either zero or one default statement.

  7. In the case of a nested switch statement, the break statements break the inner switch statement.

Point to Remember

The switch statement is preferable to multiple if statements.

No comments:

feed

PR Check

activesearchresults

judhyn's blog

 

http://www.judhyn.blogspot.com | |