c - How can I make my current code efficient by avoiding if-else conditions? -


  • programming language: c
  • platform: pic microcontroller 8-bit
  • number of problems: 2

i'm using 4-digit 7-segment display showing numbers. i've few functions display letter/digit on 7-segment like:

zero() // displays 0 on 7-segment. one() // displays 1 on 7-segment. two() // displays 2 on 7-segment. ... 

now i've number (say 1435) shown on 7-segment display. current algorithm follow:

  1. extract individual digits number 1435 (that's separate digits 1, 4, 3, 5). sds

    • 1 displayed digit1 of 7-segment.
    • 4 displayed digit2 of 7-segment.
    • 3 displayed digit3 of 7-segment.
    • 5 displayed digit4 of 7-segment.
  2. to display these individual digits, i'm using 'ten' if-else conditions follow:

    • if digit displayed == 0 -> run function zero(); else
    • if digit displayed == 1 -> run function one(); else
    • if digit displayed == 2 -> run function two();
    • ...
    • ...
    • ...

so implementation (for number 1435) printed runs several if-else checks.

  • 2 checks displaying digit 1
  • 5 checks displaying digit 4
  • 4 checks displaying digit 3
  • 6 checks displaying digit 5
  • 17 total checks run "periodically , unnecessarily" in loop() function if number not changed (this problem number 1).

problem number 2: implementation inefficient when need increment/decrement number (1435 1436 1437 on..), number of if-else checks changed variation in numbers not smooth. means '0' first in if-else checks displays quickly. on other hand '9' last in if-else checks, has undergo ten checks before gets displayed. makes implementation slower digit displayed grows 0 towards 9. how can implement solve 2 problems?

thanks in advance.

you can use pointers functions in table :

typedef void (*func)(); // type functions func functions[] = { zero, one, two, three, ... } functions[3](); // example, call three() 

you have extract digit want , use index in table....


Comments

Popular posts from this blog

java - pagination of xlsx file to XSSFworkbook using apache POI -

Unlimited choices in BASH case statement -

apache - How do I stop my index.php being run twice for every user -