9.2.2 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.
Post-decrements in conditional statement | Pre-decrements in conditional statement | |
---|---|---|
C source code |
|
|
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 |
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.