The Case Control Structure Flashcards
switch-case-default
Allows us to make decisions from many choices.
switch (int output Exp)
case (constant 1) : { statement(s); }
break;
case (constant 2) : { statement(s); }
break;
default : { statement(s); }
If no case satisfied then default is executed. Case satisfied when that int matches with constant of case.
Use of break in switch-case-default
Its use is optional. If break is not used then the case which satisfies will get executed and all the subsequent cases and finally default.
Some tips of switch:
- Order of cases can be random.
2. u can use char value in case and switch. As said before, the use of ASCII values happens.
Execute the same set of Statements for multiple cases:
switch (int output Exp) case (constant 1): case (constant 2) : { statement(s); } break; case (constant 3): case (constant 4) : { statement(s); } break; default : { statement(s); }
Cuz remember once a case satisfied everything is executed until break is encountered or switch block completes.
Braces and case?
Well no need of braces for a block of case, cuz since satisfied it will run till break occurs or switch block is completed. But u can, y not, for neatness.
What if there is a statement which does not belong to any case?
Then compiler won’t report an error but its never executed.
What if no default case:
then program simply falls through entire switch and instruction after the closing brace of switch is executed if any.
Advantage of if Over Switch:
The case cant be i <= 20, it has be something that gets evaluated to int or char value not even float.
Advantage of switch over if:
Neat, easy life.
more so if multiple statements within each case.
Case expressions:
constant exp allowed.
case a + b: invalid
case 3+7: valid.
Continue and switch:
use of continue will not take the control to the beginning of switch.
nested switch:
Allowed but not preferred.
same expressions case?
It illegal.
Why is switch used even though it has so many limitations:
execution of switch by compiler:
Compiler generates a jump table for switch during compilation. compiler simply looks at jump table to decide which case to execute rather than actually checking if each case is satisfied.
Lookup in a jump table is faster than evaluation of a condition (10)especially complex one.
but simple and less conditions (2) in if-else would work faster than corresponding switch.
exit() function:
Standard lib function.
Terminates the execution of the program.