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.

While loops optimized out by the compiler? question

Part Number: MSP430F5510


Tool/software: TI C/C++ Compiler

Hello, I am seeing some weird behavior out a program and it seems to boil down to the compiler optimizing out some while loops? my original code had the single line (ie loop2 and did not work properly) I changed it similar to LOOP1 and now it works properly, is this due to a level of optimization on the compiler? is this a known challenge (ie empty while structures?)

//------------------------------ [LOOP1]------------------------------------

// This seems to work

while (comm_flags & RAN_Busy_flag){ // Yield if RAN is busy

      __no_operation(); //

}

//------------------------------ [LOOP2]------------------------------------

// This seems to be optimized out or ignored by the compiler?

while (comm_flags & RAN_Busy_flag);

thanks in avance.

  • How do comm_flags and RAN_Busy_flag change?

    If it is done in an interrupt or another process, the MCU has no way of knowing that they will change outside of its control, so it assumes that their values *never* change and are known at run-time.

    This is what the volatile keyword is for. This will let the compiler know that some other process can change these values.
  • Hello Keith, thanks for taking the time to reply to this, and that is an excellent question, comm_flags is a volatile global variable, RAN_Busy_Flag is one of it's bits and it is updated by an interruption.

    volatile uint16_t comm_flags = 0x0005;

    Thanks
  • How are you defining RAN_Busy_flag? If it is a define, try putting it directly in the while(). i.e., comm_flags&0x01.

    If that works, you might have found a compiler bug.
  • There is another possibility to consider.   Please learn the distinction between the declaration and the definition of a global variable by reading this FAQ (not from TI).

    This is the definition of comm_flags ...

    Luis Flores said:
    volatile uint16_t comm_flags = 0x0005;

    It must appear once in some C source file.  Be sure the declaration also uses volatile.  Like this ...

    extern volatile uint16_t comm_flags;

    This declaration usually appears in a header file that is included by all the source files that read or write to comm_flags.

    Thanks and regards,

    -George