Tip #9 Conditional Statement

Usually pre-decrement and post-decrement (or pre-increment and post-increment) in normal code lines make no difference. For example, "i--;" and "--i;" simply generate the same code. However, using these operators as loop indices and in conditional statements make the generated code different.

As stated in Tip#3, using decrementing loop index results in a smaller code size. This is also helpful to get faster execution in conditional statements.

Furthermore, pre-decrement and post-decrement also have different results. From the table below, we can see that faster code is generated with a pre-decrement conditional statement. The cycle counter value here represents execution time of the longest loop.

Table 1. Example of Conditional Statement
Post-decrements in conditional statement Pre-decrements in conditional statement
C source code
#include <avr/io.h>
int main(void)
{
uint8_t loop_cnt = 9;
 do {
if (loop_cnt--) {
 PORTC ^= 0x01;
} else {
PORTB ^= 0x01;
loop_cnt = 9;
}
} while (1);
}
#include <avr/io.h>
int main(void)
{
uint8_t loop_cnt = 10;
do {
if (--loop_cnt) {
PORTC ^= 0x01;
} else {
PORTB ^= 0x01;
loop_cnt = 10;
}
} while (1);
}
AVR Memory Usage

Program: 104 bytes (1.3% Full)

(.text + .data + .bootloader)

Data: 0 bytes (0.0% Full)

(.data + .bss + .noinit)

Program: 102 bytes (1.2% Full)

(.text + .data + .bootloader)

Data: 0 bytes (0.0% Full)

(.data + .bss + .noinit)

Cycle counter 75 61
Compiler optimization level -O3 -O3
The "loop_cnt" is assigned with different values in the two examples to make sure the examples work the same: PORTC0 is toggled nine times while POTRB0 is toggled once in each turn.