if else convert to case problem

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
[PIC] if else convert to case problem

i have some difficulties i converting if else to switch statement
pls help me with this, is it posibble to use variable case?
Code:
if(distance>=0 && distance<=250)
{
LATDbits.LATD0=1;
}

else if(distance>=251 && distance<=500)
{
LATDbits.LATD0=1;
Delay10KTCYx(25);
LATDbits.LATD0=0;
}

else if (distance>=501 && distance<=1000)
{
LATDbits.LATD0=1;
Delay10KTCYx(25);
Delay10KTCYx(25);
Delay10KTCYx(25);
LATDbits.LATD0=0;
}

else
{
}
 

Switch statement doesn't make much sense here. You can however omit redundant conditions.


Code C - [expand]
1
2
3
4
5
6
7
if(distance>=0 && distance<=250)
...
else if(distance<=500)
...
else if (distance<=1000)
...
else



If distance is an unsigned quantity, >= 0 is also redundant (and hopefully already removed by the compiler).
 

If distance can be negative then the code suggested by FvM isn't quite the same.

no you can not use a variable case.


assuming distance is >= zero...............

If you insisted you could divide distance by 250, though it is not quite the same
Code:
int dis

dis = distance / 250;

switch ( dis )
{
    case 0 : ........................ break    /* distance values of 0 to 249 */
    case 1:  .........................break    /* distance values of 250 to 499 */
    case 2:                                       /* distance values of 500 to 1000 */
    case 3:
    case 4: ...........................break
    
etc
}

- - - Updated - - -

or ..............faster though not the same break points

dis = distance >> 8 /* divide by 256 */
 
Last edited:

If distance can be negative then the code suggested by FvM isn't quite the same.

True indeed, so we would use this construct to avoid redundancies.

Code C - [expand]
1
2
3
4
5
6
7
8
9
if (distance < 0)
...
else if(distance<=250)
...
else if(distance<=500)
...
else if (distance<=1000)
...
else

 

Status
Not open for further replies.

Similar threads

Cookies are required to use this site. You must accept them to continue using the site. Learn more…