MY mENU


Wednesday, 15 February 2012

Switch Statement in C



switch statement:
 Switch statements simulate the use of multiple if statement.The switch statement is probably the single most syntactically awkward and error-prone feature of the C language. Syntax of c switch statement is
switch(expression)
          {
          case constant1:
                       statements 1;
           break;
           case constant2:
                       statements 2;
           break;
           …………………..
          default:
                       statements n;
           break;
          }


                  When the switch statement is executed, the expression in the switch statement is evaluated and the control is transferred directly to the group of statements whose case label value matches the value of the expression. Each group of statement ends with a break statement. The execution of break statement causes immediate exit from the switch statement. If break statement is not present, then the execution will falls trough all the statement in the selected case.  If none of the case-label value matches the value of expression, then none of the group within the switch statement will be selected and the control is transferred directly to the statement that follows the switch statement c.


                  The expression that forms the argument of switch is evaluated to either char or integer. Similarly the constant expression follows the keyword case should be a value int or char. That is, names of variable can also be used. Switch can test for only equality.



When case constants are evaluated from the top to down, and the first case constant that matches the switch's expression is the execution entry point. In other words, once a case constant is matched, C will execute the associated code block, and all subsequent code blocks .

Example:




goto statement:

The goto statement is used to alter the normal sequence of program execution by transferring control to some other part of the program unconditionally. In its general form, the goto statement is written as


goto label;
               where the label is an identifier that is used to label the target statement to which the control is transferred. Control may be transferred to anywhere within the current function. The target statement must be labeled, and a colon must follow the label. Thus the target statement will appear as
label:statement;


Each labeled statement within the function must have a unique label, i.e., no two statement can have the same label.




No comments:

Post a Comment