This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

for loop decrement fails?

I am experiencing this weird behavior with a for loop.  I want to use a decrementing loop for efficiency's sake.  In this case just for a timer delay.

When I run this it works fine. for(i=0; i< 20000; i++); 

When I run this it fails to count and drops out of the loop immediately. for(i=20000; i>0; i--);

I'm compiling with CCS v5.5 and the full code for main.c is..

#include <msp430.h>

unsigned int i = 0;

void main(void) {
      WDTCTL = WDTPW + WDTHOLD;

      P1DIR |= 0x41;
      P1OUT = 0x40;

      for (;;)                    
      {
        P1OUT ^= 0x41;
        for(i=20000; i>0; i--);   // problem line here
      }
}

I'm new to CCS and the MSP430 but I'm pretty sure there is nothing wrong with the for loop right?.  One thing I did note is that if i open up the for loop by adding some irrelevant step inside brackets such as assigning another variable j = i then the decrementing loop works.

       for(i=20000; i>0; i--){
           j = i;
       }

What's going on here?

                 

  • kroml8r said:
    What's going on here?

    Everything is fine, compiler optimization is going on - your empty dummy loop was discarded as superflous code. When you add variable manipulation in the loop body, then it is no superflous anymore, from compiler point of view.

    To avoid such pitfalls you shall use __delay_cycles() instead.

  • Thanks for the tip on __delay_cycles(), I will certainly consider using that instead.

    What you describe makes sense for the decrementing for loop.  The compiler does not seem to consider the dummy incrementing loop as superfluous though.  Is that because the incrementing loop requires an additional function to compare the value against the ceiling whereas the decrement only has to compare against the constant 0?

  • There's no difference between increment or decrement in for() loops - from optimization point of view. What's important - presence of seemingly useful code (variable manipulations or f. calls and so on) in loop body.

**Attention** This is a public forum