Ask HN: How to trace a void recursive function?

1 points by shivajikobardan 13 hours ago

I was going over [this](https://stackoverflow.com/questions/66712061/how-do-i-trace-a-recursive-function-with-a-return-function-in-it) link. And suddenly I remembered a problem that I faced yesterday. It was related to tracing of a void returning recursive function with a printer.

Eg(pseudocode)

    func(int x)
    {
    if(x>0){
    
    print(before execution:x);
    
    func(x-1);
    
    print(after execution: x);
    }
    }

Call this function with x=5

    Before execution n=5 
    Before execution n=4 
    Before execution n=3 
    Before execution n=2 
    Before execution n=1 
    After execution n=1 
    After execution n=2 
    After execution n=3 
    After execution n=4 
    After execution n=5 
    
The output will appear like this.

Before execution part is not suprising. It is pretty obvious. But after execution part is noteworthy for me specially.

I can naively guess that it is a call stack that is being used. And it is just popping the value from the top of the stack that was pushed earlier. But I am not exactly sure of the architecture of data structure that is being used and methodologies that are being followed at code and hardware level. As a CS enthusiast, it is my basic need to understand this. Hope to get some insights here.

austin-cheney 12 hours ago

The common answer is a stack trace. In JavaScript you can get that any time and any where with:

    new Error().stack;
Stack traces lose their helpfulness in applications with high frequency network traffic because the network buffer will likely not be the start of flow control but a stack trace cannot run deeper than that.
  • shivajikobardan 12 hours ago

    I realized I do not understand how function calls use stack (exactly and accurately I mean I can imagine some stack push pop happening). Any guidance for resources? I seeked in google but turns out most materials are related to assembly language programming which I have no idea about.

    • austin-cheney 10 hours ago

      A stack trace just lists the steps an application went through by calls to non primitive references. This varies pretty significantly by language. An item in the stack is a step in memory. That is about as much as I know.