This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

Recursion in embedded system

Hi,
Can anybody give an insight whether this is good or not in embedded environment?
I have a function which call itself when a condition is false, see code sample below:

void Test(void)
{
   U8 temp;
   U8 temp1;
   U16 temp2;
   U16 temp3;

   if(some_extern_flag)
   {
      //Exit to this function
   }
   else
   {
     Test();   //Call me again
   }
}

Does it create memory leak when called many times, say 5 times the flag is false, it will call itself 5x?
This function doesn't called from either ISR or other function, just within it.
Will this create a problem later on?

thanks
gp

Parents
  • Another thing is that the above case may not result in any recursion, depending on if the specific compiler supports optimization for tail-end recursion, i.e. when the function is calling itself directly before exiting. Then the recursive call can be replaced with a jump to the start of the function, basically modifying the function into:

    void Test(void)
    {
       U8 temp;
       U8 temp1;
       U16 temp2;
       U16 temp3;
    
       for (;;) {
            if(some_extern_flag) {
                //Exit to this function
                return;
           } else {
                continue;    // Instead of recursion, just restart our loop.
           }
           break;
        }
    }
    

Reply
  • Another thing is that the above case may not result in any recursion, depending on if the specific compiler supports optimization for tail-end recursion, i.e. when the function is calling itself directly before exiting. Then the recursive call can be replaced with a jump to the start of the function, basically modifying the function into:

    void Test(void)
    {
       U8 temp;
       U8 temp1;
       U16 temp2;
       U16 temp3;
    
       for (;;) {
            if(some_extern_flag) {
                //Exit to this function
                return;
           } else {
                continue;    // Instead of recursion, just restart our loop.
           }
           break;
        }
    }
    

Children