Return statement in an infinite loop

Stumpyhuck29 picture Stumpyhuck29 · Mar 25, 2014 · Viewed 8.6k times · Source

Where does this return statement return to if it is inside this infinite while(1) loop? More importantly, I had no idea that a while(1) loop could be broken???

void __attribute__((interrupt, no_auto_psv)) _T3Interrupt(void)
{
int count;

    IFS0bits.T3IF = 0;          // clear Tmr3 interrupt flag

    StopMotor();
    IEC0bits.ADIE = 0;          // disable ADC interrupt
    IEC0bits.CNIE = 0;          // disable CN interrupt
    IEC0bits.T3IE = 0;          // disable Tmr3 interrupt

    T3CONbits.TON = 1;          // restart tmr3
    count = 0;

    while (1)
    {
        if (IFS0bits.T3IF)
        {
            IFS0bits.T3IF = 0;  // clear flag
            if (count++ >= RESTART_COUNT)
            {
                IEC0bits.ADIE = 1;          // enable ADC interrupt
                IEC0bits.CNIE = 1;          // enable CN interrupt
                T3CONbits.TON = 0;          // stop tmr3
                IEC0bits.T3IE = 1;          // enable Tmr3 interrupt
                return;
            }
        }
    }
    return;
}

Answer

ApproachingDarknessFish picture ApproachingDarknessFish · Mar 25, 2014

All return statements will return to wherever the function was called from, regardless of where they are located within the function.

For instance, if I wrote:

int main()
{
    _iT3Interrupt();

}

Then the return statement in _iT3Interrupt will revert control flow back to main.

Also, any loop can be exited (even if the condition is 1, true, or some equivalent) with any of the following constructs:

break; //exits the loop

return; //exits the function, thus ending the loop

goto <label-outside-loop>; //self-explanatory

exit(); abort(); //exits the program. Bit of a stretch to say that this ends the loop...

And in C++, throw, which will unwind the stack until it reaches a corresponding catch, thus exiting the function. The C setjmp and longjmp functions may also be applicable here, but I don't know enough C to be certain of their usage.