user19961
user19961

Reputation: 3

While loop does not break even after the condition is satisfied, but same code starts working if I use a "printf" in the while loop

I will first explain the situation :

  1. This is a menu driven program in which the option selected keep on executing until other option is fed
  2. The option is fed to the microcontroller through USB port and an ISR calls the function that handles the parsing of the input command
  3. The program runs just fine as long as the option that enters the infinite while loop is entered
  4. After it enters infinite loop it can not break from it even if the command to stop the program is entered.
  5. The Program DOES ENTER the ISR even when it is executing the while loop as has been checked by using a printf in the ISR.
  6. When command to stop the program is encountered in ISR it sets the flag which is checked by the while loop.
  7. NOW for the weird part. The same code starts working if I insert a printf("%u",command) in the while loop.

The sudo code is as follows :

ISR_USB()
{
    char command=read_from_buffer();
    printf("Entered ISR and command = %c",command); // Prints on serial port and confirms the program entered ISR 
    if(command==STOP_DEMO)
        FLAG_TO_BREAK_WHILE=true;
    printf("%u",FLAG_TO_BREAK_WHILE); // Confirms correct value of flag is set
    command_parser(command);
 }

 command_parser(command)
{
    if(command=='1')
         printf("HELLO WORLD");
    else if(command=='2')
    {
        printf("While started");
        while(!FLAG_TO_BREAK_WHILE); // Gets stuck here 
        /*
         starts working if the above while is replaced by :
         while(!FLAG_TO_BREAK_WHILE)
         {
          printf("%u",FLAG_TO_BREAK_WHILE);
          }
        */
    }
    else if (command=='3')
        printf("stop command executed");
}

please help me understand the situation here and this behavior.

NOTE: THE PARSER IS IN ANOTHER FILE AND THE VARIABLES ARE EXTERNED.

Upvotes: 0

Views: 797

Answers (1)

afic
afic

Reputation: 520

What is happening is that while(!FLAG) is being optimized to

if(!FLAG)
{
    while(true)
    {
         //do stuff
    }
}

To fix this define the flag as volatile and the compiler will be forced to read the flag from memory every time it is accessed by your code.

Upvotes: 5

Related Questions