How to break an infinite for(;;) loop in C?

NLed picture NLed · Feb 13, 2012 · Viewed 17.4k times · Source

I have a vital infinite for loop that allows a sensor to keep updating its values. However I would like to break that for loop when another sensor brings in new values. How can I switch from one infinite for loop to another?

Current code:

for(;;){

    SON_Start();
    // Wait 65ms for max range time
    delay10ms(7);
    // Read Range
    i = SON_Read(SON_ADDRESSES[sonarReading]);
    // pause
    delayMs(100);
        if(i<15)
        drive(200, RadCW);

    }

What I would like to add:

If Sensor2 returns a reading (e.g. Sensor2 > 20), then I want to break the loop and goto another infinite for loop to begin a new function.

Answer

LihO picture LihO · Feb 13, 2012

If you are looking for "switching between 2 infinite loops" it could be "wrapped" by third loop and this "switching" could be done by simple break.

But since you want your program to stop some day, this loop could be placed within the function and you could use return; for ending it:

void myMagicLoop()
{
    for(;;)
    {
        for(;;)
        {
            if ( I should stop )
                return;

            if ( I should switch to second loop )
                break;
        }
        for(;;)
        {
            if ( I should stop )
                return;

            if ( I should switch back to first loop)
                break;
        }
    }
}

And somewhere you just call:

myMagicLoop();

Hope this helps.