Switch –case statement generally to check the value of an integer with different discrete possibilities. Let us plan to have a menu driven program where there is a variable called int menu_selection, which can have values like 0, 1, 2, 3, -1, etc as user selection value. Now say 0 means new student addition, 1 means edit record, 2 means display record and -1 means exit to previous menu. Here we trying to implement this with if-else-if statement.
This type of comparison with discrete values is best suited for a switch case. Now we will re-write the above logic in a more managed way. Here point to remember is if-else-if statements are used mainly to check integer range values and switch is used to check distinct values.
Please note: Placing a break at the end of a case is optional. Not putting break in one case causes control to go to the next case block unconditionally. In our example we can remove the break after edit_record(). This will take the control to go to display_record (); after an edit.
Also note there is no break at the end of default case. Default case is the last case block thus control is supposed to go to the end of switch and hence break is not required here. Even if putting a break will not cause any error either.
About our authors: Team EQA
You have viewed 1 page out of 248. Your C learning is 0.00% complete. Login to check your learning progress.
Questions index C Questions C++ Questions Win32 MFC COM/DCOM DLL Questions
Compilers & Editors
Download Visual Studio Download XCode Download Visual Studio Code Android studio install sdk Eclipse installer Best C compilers IDEs
Development system setup
Windows media creation tool MSDN subscription Ubuntu virtualbox
New updated posts
Why learn C? Calculate weighted average