[SOLVED] Switch statement difficulties

Status
Not open for further replies.

ruben91

Junior Member level 3
Joined
Nov 17, 2014
Messages
29
Helped
0
Reputation
0
Reaction score
0
Trophy points
1
Visit site
Activity points
209
i have done an if statement in my project, it worked fine but quite laggy as it takes time to read, so i planned to change it to switch case statement bt i seem to get error i compiling, pls help me to solve this
here is my code
if(distance>=0 && distance<=250)
{
PORTDbits.RD2=1;
}

if(distance>=251 && distance<=500)
{
PORTDbits.RD3=1;
}

if (distance>=501 && distance<=1000)
{
PORTDbits.RD0=1;
}

if(distance>=1001)
{
PORTDbits.RD1=1;
}

this is my coverted switch statement
bt i get error in compiling
 

Code:
if(distance>=0 && distance<=250)
{
PORTDbits.RD2=1;
}

else if(distance>=251 && distance<=500)
{
PORTDbits.RD3=1;
}

else if (distance>=501 && distance<=1000)
{
PORTDbits.RD0=1;
}

else if(distance>=1001)
{
PORTDbits.RD1=1;
} 
else
{


}

your if statement should be like that and your switch conversion is totally wrong.
 
Code:
if (distance>=0 )
{ 
if (distance<=250)
{
PORTDbits.RD2=1;
}

else if(distance<=500)
{
PORTDbits.RD3=1;
}

else if (distance<=1000)
{
PORTDbits.RD0=1;
}
else 
{
PORTDbits.RD1=1;
}
}
indentation is lousy but you get the idea
 
In a switch/case statement the 'case' must equate to a constant, you can't use variables I'm afraid.
You might also need to consider what happens to the other outputs when the distance is not between the limits.

Brian.
 
Switch case requires constant value, if you have predefined value, then can do like below(just an example), otherwise if else is the best i believe or do it in assembly to optimize the code.
Code:
switch(input){

    case 0:
    case 150:
    case 250:
                PORTDbits.RD2=1;
        break;

    case 400:
    case 500:
                PORTDbits.RD3=1;
        break;

      default:
                PORTDbits.RD1=1;   
}
 
The other way you can optimize the code is to work from the highest value down using 'if' statements and put it in a function. It reduces the number of calculations needed to check the value.

For example:
Code:
void MyFunction()
{
 if(distance > 1000) {PORTDbits.RD4 = 1; return;}
 if(distance > 500) {PORTDbits.RD3 = 1; return;}
 if(distance > 250) {PORTDbits.RD2 = 1; return;}
 PORTDbits.RD1 =1;
}
which should do the same thing.

Brian.
 
Status
Not open for further replies.
Cookies are required to use this site. You must accept them to continue using the site. Learn more…