Monday, May 24, 2010

C++ switch/case???

can someone please explain how switch/case works in c++ and give an easy example? im a beginner

C++ switch/case???
The previous example by ale8oneboy is good. I just wanted to say a couple things. First his example has a "default" statement at the end of the switch. This is used to catch any anything that is not caught by other cases. It is often used as a way to catch an error.


Next, you have to notice that he has a 'break' command. The break command tells the program that the things needed to do in this case are complete. Without it, it would do the actions for the cases below it, until it hit a 'break' command or it go to the end of the switch. For example, if he were to take out the break in case 1 and the user entered 1 as the input, then the output would be REDBLUE. However, if the user entered 2, then it would print BLUE as expected. This is a common place to find a problem when debugging. However, this is also useful if you want to save lines of code when many cases do the same thing. for example,





case 'A':


case 'B':


case 'C':


doFunction();


break;





is the same as





case 'A':


doFunction();


break;


case 'B':


doFunction();


break;


case 'C':


doFunction();


break;
Reply:Switch case is pretty simple. Switch case is used in place of IF...Then statements in the event there is more then 2 or more possible values for a variable.





//Example: User inputs color 1=Red 2=Blue, 3=Green





int color %26lt;%26lt; cint;





switch (color ) {





case 1 :


cout %26gt;%26gt; "RED";


break;





case 2 :


cout %26gt;%26gt; "BLUE";


break;


case 3 :


cout %26gt;%26gt; "GREEN";


break;





default :


cout %26gt;%26gt; "UNKNOWN COLOR";


...





}


No comments:

Post a Comment