Page 1 of 1

Using switch(variable) instead of if statements?

PostPosted: Wed Aug 01, 2012 11:56 pm
by happyjustbecause
Is it at all bad to do something like this:

Code: Select all
switch(state)
{
    case 0:
    r=255;
    break;

    case 1:
    r=125;
    break;

    case 2:
    r=0;
    break;
}


In this there is no actual switching of the variable state, but it still acts as if statements, saying if case 0 (if state==0) run this code. What if I want to have this format, but I don't want to actual change the value of the variable. Is it bad to do this? I realize this isn't switching the variable, but it provides a nice way to prevent a lot of if statements, and it looks nicer to me. Is there some other way to have this format of case 0, case 1, case 2 etc. rather than if(state==0), if(state==1), if(state==2)

Re: Using switch(variable) instead of if statements?

PostPosted: Thu Aug 02, 2012 2:36 am
by AliceXIII
switches are made and meant to avoid using if's in some cases as in with a switch you can do this:
Code: Select all
int var=rand(5);
switch(var)
{
    case 0:
    //do something here
    break;
    case 1:
    //do something here
    break;
    case 2:
    //do something here
    break;
    case 3:
    //do something here
    break;
    case 4:
    //do something here
    break;
}

as i see you understand the usage of a switch like the above example^^

the way a switch reads variables is it reads specific numbers you tell it like case 5: but it can't do this:
Code: Select all
if(var>=5)
{
    //do something here
}


so switches only read like if's in the sense of using the == operator in an if statement
any other sense of variable reading you'll need to use an if, while, or for loop..

In this there is no actual switching of the variable state, but it still acts as if statements, saying if case 0 (if state==0) run this code. What if I want to have this format, but I don't want to actual change the value of the variable. Is it bad to do this? I realize this isn't switching the variable, but it provides a nice way to prevent a lot of if statements, and it looks nicer to me. Is there some other way to have this format of case 0, case 1, case 2 etc. rather than if(state==0), if(state==1), if(state==2)


^^well you have to have your variable switch in order for the switch itself to run the code in side a certain case..

hope this helped any other specific questions on differn't operators or statements in c/GE your welcome to pm me :)

Re: Using switch(variable) instead of if statements?

PostPosted: Thu Aug 02, 2012 2:55 am
by happyjustbecause
Oh okay, I didn't know that other people used the switch instead of if statements. I was just wondering if there was a better way to have it, or if I'm not being "proper", by not using the function the way it's supposed to be used. Anyways thank you for the clarification. :)