View previous topic :: View next topic |
Author |
Message |
Marc Guest
|
question about c language |
Posted: Thu Jul 12, 2007 8:16 am |
|
|
I need to simplify the code
if (va>=817) in=0;
else if ((va>=750) && (va>760)) in=3;
else if ((va>=730) && (va>740)) in=4;
else if ((va>=710) && (va>718)) in=5;
else if ((va>=685) && (va>695)) in=6;
else if ((va>=665) && (va>675)) in=7;
else if ((va>=645) && (va>655)) in=8;
else...
How can I use switch...case in this situation?
Thank You |
|
|
SherpaDoug
Joined: 07 Sep 2003 Posts: 1640 Location: Cape Cod Mass USA
|
|
Posted: Thu Jul 12, 2007 9:38 am |
|
|
Beware switch statements usually take an int. 817 doesn't fit in a CCS int. I don't know if CCS lets you use something larger than an int. _________________ The search for better is endless. Instead simply find very good and get the job done. |
|
|
inservi
Joined: 13 May 2007 Posts: 128
|
|
Posted: Fri Jul 13, 2007 1:34 pm |
|
|
Hello Marc,
Is that real code used in your program ?
dro. _________________ in médio virtus |
|
|
libor
Joined: 14 Dec 2004 Posts: 288 Location: Hungary
|
|
Posted: Sun Jul 15, 2007 3:21 am |
|
|
You made a typo I think, the second > would have been < .
To the point: I would use a lookup table and make the quantization in a loop rather then to have that many if elseif-s.
declare a const array with the range values, and find the range in a loop the value fits in. This makes the code more maintanable also. |
|
|
ckielstra
Joined: 18 Mar 2004 Posts: 3680 Location: The Netherlands
|
|
Posted: Sun Jul 15, 2007 5:55 am |
|
|
Another problem with the given example code is that there are gaps in between the tested ranges. For example 740 - 750 is not handled while I suspect that's not what the programmer intended.
If there are indeed no gaps intended the test can be simplified as: Code: | if (va>=817) in=0;
else if (va>=750) in=3;
else if (va>=730) in=4;
else if (va>=710) in=5;
else if (va>=685) in=6;
else if (va>=665) in=7;
else if (va>=645) in=8;
else... |
Quote: | To the point: I would use a lookup table and make the quantization in a loop rather then to have that many if elseif-s.
declare a const array with the range values, and find the range in a loop the value fits in. This makes the code more maintanable also. | A very nice suggestion. The if-else construction will be more memory efficient when only a few ranges have to be detected, lets say up to a maximum of 10 - 15 tests. |
|
|
|