Home > Enterprise >  How do I break, from outside of a loop in C?
How do I break, from outside of a loop in C?

Time:01-10

I have a code:

void core()
{
   loop
   {
   first_process();
   secound_process();
   
   process_synchronizer();
   }
some_other_job();
}

In the process suynchronizer() I evaluate synchronization and if the criterion has not beeing satisfied it will break the loop. The problem is the break is not allowed in that function since it's not in the loop.

void process_synchronizer()
{
   if(criterion)
      do something;
   else
      break;
}

But the break is not allowed there by the c compiler: break statement not within loop or switch

CodePudding user response:

like this:

void core()
{
   bool exit_flag = false
   while (!exit_flag)
   {
       first_process(&exit_flag);
       if (!exit_flag)
           secound_process(&exit_flag);
       if (!exit_flag)
           process_synchronizer(&exit_flag);
   }
}

Or this:

void core()
{
   bool exit_flag = false
   while (!exit_flag)
   {
       exit_flag = first_process();
       if (!exit_flag)
           exit_flag = secound_process();
       if (!exit_flag)
           exit_flag = process_synchronizer();
   }
}

Then adjust your functions to return the appropriate value. Like this:

bool process_synchronizer()
{
   if(criterion)
      do something;
      return false;
   else
      return true;
}
  • Related