10 C Language Tips for Hardware Engineers
Tip #1 – Don’t use “goto” statements
A couple decades or so ago when computer programming was in its’ infancy, a programs flow was controlled by “goto” statements. These statements allowed a programmer to break the current line of code and literally go to a different section of code. A simple example of this can be seen in Listing 1.
Listing 1: Use of goto statement
Listing 2: Using a function to control flow
Tip #2 – Use for(;;) or while(1)
If goto’s are out, some hardware engineers may wonder how an infinite loop can be created for the program. After all, this may have been done before by creating a goto statement that returns back to the top of main. The answer is to take advantage of the looping statements that are already built into the C language; for and while. Listing 3 and Listing 4 show examples of using for and while loop in this regard.
Listing 3 – Using an infinite for loop
Listing 4 – Using an infinite while loop
The loop conditionals in the listings are relatively straight forward. The for loop is nothing more than the for conditional with no conditions. The while loop on the other hand will execute as long as the statement is true which is the same as having any non-zero value for the condtion.
Tip #3 – Use the appropriate conditional statement for the job
Program execution time can be highly dependent on the type of conditional structure that is selected for making a decision in addition to the readability of the code. Many hardware engineers are familiar with the use of the simple if statement; however, sometimes the engineer doesn’t realize that if the first condition isn’t correct, an else or else if statement can be used. This can save the processor time by not having to evaluate another conditional statement. An example of this can be seen in Listing 5. In the before code, if Var is equal to one it will still check to see if the Var is equal to zero; however, in the after code that uses the else, only the first statement is evaluated and then the code moves on, thereby saving clock cycles and making the code clearer.
Listing 5 – Using if/else instead of just if
The if/else if/else statements still may not always be appropriate. If there are a number of possible conditions that need to be checked, a switch statement may be more appropriate. This allows the processor to evaluate the statement and then select from a list of answers what it should do next rather than continually evaluating a bunch of conditions. An example can be seen in Listing 6 that corresponds to the same type of example shown in Listing 5.
Listing 6 – Using switch statements
The moral of the story is simply to keep alternative conditional statement options open and select the most appropriate for the job at hand. This will ease in understanding the flow of the program by making the structure straight forward and could squeeze extra clock cycles out of the processor.