Home › Forums › C Programming › How to avoid if else…
- This topic has 3 replies, 4 voices, and was last updated 15 years, 6 months ago by TWGArlette.
- AuthorPosts
- June 11, 2009 at 12:24 pm #2204ChassidGoodissoParticipant
Hello,
Problem is – User can input any number, program need to take decision based on inputs.
Let suppose input is stored in variable n;
based on value of n some function will be called.
program logic can be –if(n > 1 && n < 10 )
callfun1();
if(n > 11 && n < 20 )
callfun2();
if(n > 25 && n < 30 )
callfun3();
if(n > 33 && n < 38 )
callfun4();
if(n > 1 && n < 10 )
callfun5();
.
.
.
and so on
if(n > minlimit && n < maxlimit )
callfunX();Is there any easy way to avoid if else chain to do similar work.
Or is there any way to change the limits in if condition at some central place something using #define.Please provide your inputs/help to help me finding other ways to optimize programming.
Thank
Vikas - June 11, 2009 at 8:34 pm #3580GWILouisaxwzklaParticipant
This is really the only way to do this in C ( if your decision was based on constants I would suggest a “switch” statement ). You could could also use “goto”‘s and lables but this would be bad programming practice and the compiler will generate the same type of code at the assembly level anyway. You could also use “function pointers” in an array and make the variable ‘n’ index this array and then call the proper function , but this might be a waste of memory even thought you avoid testing a value for each “if” statement. I’d probably stick with the “if” chain ……..
- June 15, 2009 at 6:40 am #3581IdaDonaldxParticipant
HI FRIEND … THIS IS DAVID… I AGREED WITH DMAN… WHAT HE SAID IS RIGHT ONLY WAY IS TO USE SWITCH CASE …
- June 15, 2009 at 3:14 pm #3582TWGArletteParticipant
Nice thread. I find this useful when using C++ since I’m a beginner at the program. Thanks a lot for the information!
- AuthorPosts
- The forum ‘C Programming’ is closed to new topics and replies.