Using stack memory with an arithmetic and recursive function call

My concern is that it will use the stack memory in an instruction involving arithmetic and calling a recursive function, for example:

return 5 + f(a-1); //f is recursive

I would like to understand what is pushed onto the stack, and when, so that I know what may or may not cause memory problems in the case of deep recursion. Here is a more complete example:

int f(int a) {
    if (a > 0) {
        return 5 + f(a-1);
    }
    else {
        return 0;
    }
}

Focus on the line. return 5 + f(a-1);What do we need to store in memory around this point?

  • We have a stack space for an integer a, since the variable is local to f
  • Will values ​​5 and 1 be saved?
  • What about the result of operation a-1, will it be pushed onto the stack?
  • what about the return value of f?

" " , - . , , .

? ?

,

+3
4

, (, , ) a-1. 5 1 , .

, f(999999999), . a-1.

, :

int f(int a) {
    if (a <= 0) return 0;
    return 5 + f(a-1);
}

, , , , :

int f(int a) { return (a > 0) ? a * 5 : 0; }

: -)

+3

"Stack" / CPU, . , .

, : - a. - . - . - , , . , .. I. , .

return 5 + f (a-1);

5 - , . -1, , " ", , , .

a-1 , " a" .

, , , , .

+2

C

, , , while (. )

!

0

, , :

  • a , .
  • Naturally, the parameter fmust be pushed onto the stack.
  • The value 5 must be pushed onto the stack because it needs to be saved for later operation +.
  • If I remember correctly, the return value is treated as a parameter, so it will also be pushed onto the stack.
  • And, of course, an instruction pointer.

But maybe the compiler does some optimizations that I don't know about.

-3
source

Source: https://habr.com/ru/post/1788172/


All Articles