bitzero wrote:

DON'T NEST LOOPS.   IT'S WRONG.


Sorry to dredge up such an old thread, but I'd just thought I ought to comment on your hatred towards the use of nested loops. I understand that in some sections of the industry there is no real need to have nested loops in any program. However, in the embedded world it is quite useful and necessary.

For example, I'm creating a flash driver for a chip that has the following conditions to write a large chunk of data to flash:
1) After writing a word to flash, you have to wait for flash to be ready before you write the next word. Since this is only a few dozen clock cycles, waiting in a loop is proper procedure. If you wait for longer than expected, then something is wrong and you need to report an error.
2) After writing to a 64 byte block, you have to exit write mode for a short period of time.

In a PC environment, the pseudo-code to accomplish this may look like this:

bool WriteFlash()
{
   bool returnVal;
   while(still have data to write)
   {
      returnVal = WriteBlock();
      if(returnVal == FALSE)
      {
         break;
      }
   }
}

bool WriteBlock()
{
   bool returnVal;
   SetupWriteMode();
   while(still have data in block to write)
   {
      WriteWord();
      returnVal = IsFlashReady();
      if(returnVal == FALSE)
      {
         break;
      }
   }
   ExitWriteMode();
   return returnVal;
}

bool IsFlashReady()
{
   int i = 0;
   bool returnVal;
   while(flash is not ready && i < EXPECTED_WAIT)
   {
      i++;
   }
   if(i >= EXPECTED_WAIT)
   {
      returnVal = FALSE;
   }
   else
   {
      returnVal = TRUE;
   }
   return returnVal;
}

As you can see each function is rather simple and there are no nested loops. However, I'm using a 1 MHz microcontroller with 2KB of RAM (yes, chips like this are still used today), of which I only have about 400 bytes for stack space. In this envrionment, nesting functions that do next to nothing is a bad thing because of the added stack space and processing time for entering and exiting a function. For my application, this is actually a better way to write the function:

bool WriteFlash()
{
   int i=0;
   while(still have data to write)
   {
      Setup write mode // no function call
      while(still have data in block to write)
      {
         Write word // no function call
         while(flash is not ready && i < EXPECTED_WAIT)
         {
            i++;
         }
         if(i >= EXPECTED_WAIT)
         {
            return FALSE;
         }
      }
      Exit write mode // no function call
   }
   return TRUE;
}

You're probably cringing because you see I'm returning from a loop that is nested three levels deep. However, I saved about 5% of my precious stack space by using nested loops instead of nested functions.  A few instances like this makes the difference between an embedded project working or not.  In my opinion, to say something as broad as "nesting loops is wrong" is a little too definitive.