Home Forums C Programming How to avoid if else…

Viewing 3 reply threads
  • Author
    Posts
    • #2204
      ChassidGoodisso
      Participant

      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

    • #3580
      GWILouisaxwzkla
      Participant

      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 ……..

    • #3581
      IdaDonaldx
      Participant

      HI FRIEND … THIS IS DAVID… I AGREED WITH DMAN… WHAT HE SAID IS RIGHT ONLY WAY IS TO USE SWITCH CASE …

      web development services

    • #3582
      TWGArlette
      Participant

      Nice thread. I find this useful when using C++ since I’m a beginner at the program. Thanks a lot for the information!

Viewing 3 reply threads
  • The forum ‘C Programming’ is closed to new topics and replies.