Faraz Ahmad February 2016

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 a 4-digit 7-segment display for showing numbers. I've a few functions that display some letter/digit on the 7-segment like:

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

Now I've a number (say 1435) to be shown on the 7-segment display. My current algorithm is as follow:

  1. Extract individual digits from the number 1435 (that's separate the digits as 1, 4, 3, 5). sds

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

    • If the digit to be displayed == 0 -> run the function zero(); else
    • If the digit to be displayed == 1 -> run the function one(); else
    • If the digit to be displayed == 2 -> run the function two();
    • ...
    • ...
    • ...

So this implementation (for the number 1435) to be printed runs several if-else checks.

  • 2 checks for displaying the digit 1
  • 5 checks for displaying the digit 4
  • 4 checks for displaying the digit 3
  • 6 checks for displaying the digit 5
  • 17 total checks that run "periodically and unnecessarily" in the loop() function even if the number is not changed (This is problem number 1).

Problem number 2: This implementation is inefficient as when I need to increment/decrement that number (1435 to 1436 then to 1437 so on..), the number of if-else checks are also changed so the variation in numbers is not smooth<

Answers


Jean-Baptiste Yunès February 2016

You can use pointers to functions in a table :

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

You have to extract the digit you want and use it as an index in the table....

Post Status

Asked in February 2016
Viewed 2,683 times
Voted 8
Answered 1 times

Search




Leave an answer