Return statement in an infinite loop

北慕城南 提交于 2019-12-02 04:06:30

问题


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;
}

回答1:


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.




回答2:


There are multiple ways to get out of a loop with return break goto

with your snippet if IFS0bits.T3IF != 0 then it will eventually break out of the loop when count >= RESET_COUNT. After that it will return to where the function was called from.




回答3:


To answer your second question, while(1) is more like while(true). Therefore, it keeps on looping until it encounters a break.




回答4:


When a function is called the address the function (or ISR) is called from is put on the top of the stack.
The execution of return will end the function (or ISR). The programm counter (PC) is updated with this address, so the program flow could continue with the statement following the calling address.



来源:https://stackoverflow.com/questions/22645897/return-statement-in-an-infinite-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!