Home > Software engineering >  Uses of stack while calling empty recursive funcion in C
Uses of stack while calling empty recursive funcion in C

Time:07-21

Here is a simple C recursive program.

void func(void)
{
   func();
}

int main()
{
   func();
   return 0;
}
  1. Does this program use the stack in every call of func()

  2. If yes, What does it stores in stack?

CodePudding user response:

its not a terribly big program, id suggest compiling it, and running it and checking if youll get a stack overflow, okay argh.... I just tested it:

with /Od it returned resulted in overflow

with /O2 it also resulted in overflow, returning 3221225725

Tested on compiler explorer MSVC V19. latest

--what does it store in the stack? The instruction pointer / Program Counter. How else would the program know where to return to?

--whether optimized or not, the only change was the size of the function, it wont optimize the function away. Or, MSVC 19.latest wouldnt. If you find a compiler that does, that would be great for those virtual function calls to non-nothingness, which i believe is one of the critiques against them.

CodePudding user response:

  1. C standard does not know anything about the stack. So generally speaking this question does not have an answer.

  2. This function calls itself at the end of its execution. It is called tail recursion (very specific case) and most modern optimising compilers will optimise it to an infinitive loop (assuming optimisations enabled).

  3. Most implementations use the stack. Recursive functions (except tail recursion ones) will create a new stack frame on every call.

  • Related