Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

if else convert to case problem

Status
Not open for further replies.

ruben91

Junior Member level 3
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

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top