Question

I was wondering as why do we include an empty while(1) loop in the end of most c programs for example motor driver, gyro sensor routines? I searched but didn't find any satisfactory reason for this.

Thanks.

For example following code on an ATmega8:

#include <avr/io.h>
#include <util/delay.h>
void main (void)
{
int n = 1;
DDRB = 0xFF;
for (n=1; n<=10; ++n)
{
PORTB = 0x00;
_delay_ms(1000);
PORTB = 0XFF;
}
while (1)
{}
}
Was it helpful?

Solution

Many embedded systems use timers, interrupts or other events to drive their actions. They may also run OS's that provide threads or tasks that might be set up to performer he real work. So once that initialization is done, there's nothing left for the main() program to do, but in such simple systems there is often nothing for main() to return to, so an infinite do nothing loop keeps the processor busy while nothing else is happening.

OTHER TIPS

An empty while(1) loop prevents the thread from exiting. Perhaps that's what's desired by the code you are looking at.

Even in simple programs, an implementation is free to

  • restart (reset)
  • or hang

at the end of main().

You can enforce the latter behaviour by this endless loop.

If you want the program to repeat endlessly, you can as well do so.

If you don't exactly know what the library does upon return from main(), you better don't return, but loop the one or other way.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top