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 Loop & Volatile Declaration



IDE: CCS 5.3

Target: LM4F211_CNCD

Up until today I have been running some code successfully containing some while loops that are empty as shown in the example below with no issues.

........

while (bDoorClosed == false)                                            //just loop here until the door is closed and the hall sensor trips
                    {
                    }

........

Today I was trying to generate a .BIN file for flash programming and made all the appropriate changes in the post build steps with no problems, no issues there as far as generating the .BIN.  However, when I downloaded and ran the program (using standard debug in CCS) the code would hang up at each and every while loop even after the while loop condition was not met (or false).  The code would just not move on to the next line.  After messing around for a while I decided to change the definition of  "bDoorClosed" from:

tBoolean bDoorClosed = false;            //Hall sensor input set to low door is open

                  to

volatile tBoolean bDoorClosed = false;            //Hall sensor input set to low door is open

and that resolved the while loop hang up issue.

1) Did something occur when I made the changes in the post build steps?

2) What is the explanation for this behavior is it a compiler driven issue?

Thanks in advance for any help on this.

  • Any variable that is accessed both inside and outside of interrupts or in different contexts must be declared as volatile.  Otherwise the compiler is free to assume that the variable will not change between accesses, even if no optimization is enabled.  The volatile declaration basically tells the compiler that the variable can change unexpectedly or is monitored in other contexts so the compiler is not allowed to make any assumptions about it and will perform a read or write to that variable every time it's referenced in the code.

    I'm not sure what you changed in your post build operations.  Often debug builds have optimization turned off, while release builds enable optimization which can affect these things.