# switch case question

This topic is 3941 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

okay im reading up on a c++ tutorial. i have no prior programming experience so far i now understand everything pretty well. i can use if statements and else and else if i used it to make some basic programs and have a decent beginner understanding. now the next section was switch case and i just read the explanation and am very confused. so you use it only for a integral value, so does this mean you would make a variable then use switch case to let the user type something in and make that variable equal to something and then have it execute code for what they chose. for instance have if they choose yes it does this you choose no it does this you choose nothing it does this etc. if i got that right please say so. i did that with if/else statements but switch case just confuses me. lets say i wanted if the user types in 1 to have it say hello and if the user types in 2 it says goodbye is this how you do it with switch case? also whats more commonly used switch case or if statements? this example question is just to give me an understanding i just randomly am trying it, its not serious. #include <iostream> using namespace std; int main() { int input; cout<<"Enter 1 for hello and 2 for goodbye.\n"; cin>> input; switch ( input ) { case 1: input == 1; cout<<"Hello!\n"; break; case 2: loadgame(); break; default: cout<<"Error, bad input, quitting\n"; break; } cin.get(); } actually as im trying to do this im confused on even what to do where do you define what each case should equal to execute the action? i just took the example from the tutorial and was trying to add in my own stuff and deleted some stuff. in case 1 is that what i do ?(probablly not but thought id try) i did not do the second part cause as i look at this i feel like its wrong lol. anyways thanks Hey

##### Share on other sites
Yes. Basically right. There is no real difference between a switch statement and a series of if -> else if -> else if -> etc statement. It might possibly be optimized better, but I wouldn't think so. A good example would be a simple AI:

enum AIState{    STATE_IDLE,    STATE_GUARD,    STATE_ATTACK,    STATE_RETREAT};class AIDude{    //assume this gets setup correctly    AIState mState;};

void updateAI( AIDude &dude ){    switch ( dude.mState )    {        case STATE_IDLE:            //make the AI do whatever it does when it's idle            break;        case STATE_GUARD:            //make the AI do whatever it does when it's guarding            break;        case STATE_ATTACK:            //make the AI do whatever it does when it's attacking            break;        case STATE_RETREAT:            //make the AI do whatever it does when it's retreating            break;    }}

[EDIT: In case you haven't learned about them yet, enums are just a series of sequential integer values that you can give nice names to: clicky]

-me

##### Share on other sites
1) Capitalization.
2) More periods.
3) [ source ] tags for your code.

Quote:
 so you use it only for a integral value, so does this mean you would make a variable then use switch case to let the user type something in and make that variable equal to something and then have it execute code for what they chose.

switch can only be used with integral types, which means you can't use switch on a std::string or on a double, for example (even though the former at least would make a lot of sense). They're limited to thinks like enums and integers.

Quote:
 for instance have if they choose yes it does this you choose no it does this you choose nothing it does this etc. if i got that right please say so. i did that with if/else statements but switch case just confuses me.

It sounds like you have a basic understanding. These two snippets are basically equivilant:

if ( a == 0 ) foo();else if ( a == 1 ) say_hello();else if ( a == 2 ) say_goodbye();else pineapple();switch (a) {case 0: foo(); break;case 1: say_hello(); break;case 2: say_goodbye(); break;default: pineapple(); break;}

Quote:
 lets say i wanted if the user types in 1 to have it say hello and if the user types in 2 it says goodbye is this how you do it with switch case? also whats more commonly used switch case or if statements? this example question is just to give me an understanding i just randomly am trying it, its not serious.

If statements are more commonly used, since they're not limited to comparing integral types, and make more sense for boolean data. That said, switch is usually used for choosing between the possible values of an enum -- for example, the keys of a keyboard, or the event type of an SDL event.

##### Share on other sites
okay thank you i understood its similar to if and else etc but everything after that confused me lol im gonna read that thing on enums but so far i have no knowledge of ai or enums im very new to c++. thank you though if possible could you explain it with a more basic example?

thanks
hey

after i read the thing on enumbs hopefully it will make more sense to me.

-oops reading second post now just noticed it.

thanks both of you guys for the help btw

##### Share on other sites
@palidine : He said he was starting C++, don't give him enums and classes when he's trying to work out switch cases!

Ok, I'm going to try to help you there, it yould not be very complicated as, looking to your code, you seem to get much of it.

The thing you need to know is that switch cases are only used to compare values, like "==". You want to do something different for each possible value of your variable. Switch cases do not allow comparisions other than equalities, you can't compare if the value is greater than or equal, neither if it is lower than. In fact, you can compare a switch case by a group of if and else ifs which always use the same variable and compare it to different values. Because of the equality-only thing, you don't need to specify "input == 1;" as you did, we know you're comparing "input", we know you're using an equality, we only need to know that you're comparing it to 1.

Here's how a switch statement compares to multiple ifs :

int myVar = 2;// All of this...switch(myVar){case 0:doSomething();break;case 1:doSomeOtherThing();break;default:doSomeLastThing();}// ... Is equivalent to :if(myVar == 0) { doSomething(); }else if(myVar == 0) { doSomeOtherThing(); }else { doSomeLastThing(); }

I hope this helps

... now this post took a while to type I'm sure I got beaten to it...

##### Share on other sites
Quote:
 Original post by HeyHoHeythough if possible could you explain it with a more basic example?

Your example was a fine teaching example. You will generally only use switch statements, however, when there are more choices to be made:

1 - apple
2 - banana
3 - grape
4 - dandelion
switch (choice ){case 1:    std::cout << "Apples grow in New England.  They are red and delicious\n";    break;case 2:    std::cout << "What?  You're saying that you're a monkey?\n";    break;case 3:    std::cout << "Duuuude. Save the grapes for the wine!!!!\n";    break;case 3:    std::cout << "I have detected that you're an idiot.  Dandelions are flowers n00b\n";    break;}

-me

##### Share on other sites

It sounds like you have a basic understanding. These two snippets are basically equivilant:

if ( a == 0 ) foo();else if ( a == 1 ) say_hello();else if ( a == 2 ) say_goodbye();else pineapple();switch (a) {case 0: foo(); break;case 1: say_hello(); break;case 2: say_goodbye(); break;default: pineapple(); break;}

okay this is a little easier to understand the thing that still confuses me is that in if statements you clearly define what the variable needs to equal to do which action a == 0. is the equivalent in the switch case the case 0? does case 0 mean a == 0. so if i wanted something to happen if the variable was 8 would i put case 8? also is it possible to do > or < ? or is switch case only for things that are exactly equal?

thanks
hey

##### Share on other sites
OH OKAY TY TRILLIAN AND TY PAIDLINE for your last two posts. your explanation trillian cleared a LOT up in my head lol and your example paidline reinforced it. just one more question if i wanted to have something happen if its == 8 would i just do case 8? can it go out of order can i have like case 1 case 6 case 0?

thanks
hey

##### Share on other sites
Quote:
 Original post by HeyHoHey is switch case only for things that are exactly equal?

Precisely, you can't do > < >= <= !=

##### Share on other sites
Quote:
 Original post by HeyHoHeyOH OKAY TY TRILLIAN AND TY PAIDLINE for your last two posts. your explanation cleared a LOT up in my head lol and your example paidline reinforced it. just one more question if i wanted to have something happen if its == 8 would i just do case 8? can it go out of order can i have like case 1 case 6 case 0?

yes, you would do "case 8:", it basically means "if your variable is equal to 8 then do the following". The order of the numbers is not important, as long as you have no duplicates (do not have two "case 5" for exemple).

EDIT:
I'll add something. As I said, "case 8:" means "if your variable is equal to 8 then do the following UP TO THE BREAK STATEMENT". That means that you can also do an action to occur in two cases. For example :

case 6:
case 23:
helloWorld();
break;

In this example, "helloWorld" will be executed if either your variable is 6 or 23.

There's nothing you can do with switch cases that you cannot do with a couple of ifs. People tend to use switch statements only if the number of possibilities is very high. But it is still useful to know about.

##### Share on other sites
Quote:
Original post by Trillian
Quote:
 Original post by HeyHoHeyOH OKAY TY TRILLIAN AND TY PAIDLINE for your last two posts. your explanation cleared a LOT up in my head lol and your example paidline reinforced it. just one more question if i wanted to have something happen if its == 8 would i just do case 8? can it go out of order can i have like case 1 case 6 case 0?

yes, you would do "case 8:", it basically means "if your variable is equal to 8 then do the following". The order of the numbers is not important, as long as you have no duplicates (do not have two "case 5" for exemple).

okay thank you so much trillian i think i decently grasp this concept now. :). im about to go try and make a basic program to try and use switch case.

thanks again
hey