recursionpostfix-operator

how --x works fine in this code but x-- gets StackOverflowError


private static int fib(int zero, int one, int x, int s) {
    if(x==0) return s;
    zero = one;
    one = s;
    s= zero + one;
    return fib(zero,one,x--,s);
 }


     private static int fib(int zero, int one, int x, int s) { 
    if(x==0) return s;
    zero = one;
    one = s;
    s= zero + one;
    return fib(zero,one,--x,s);
    }

In this code please expalin why x-- gets stackoverflowerror and --x don't.


Solution

  • The first question to ask is: "Do you understand what the -- operator is doing differently in each scenario?"

    In C-like languages:

    SomeFunction(arg1, arg2, --x); is equivalent to:

    x = x - 1; // x is updated
    SomeFunction(arg1, arg2, x); // use updated x
    

    While conversely: SomeFunction(arg1, arg2, x--); is equivalent to:

    SomeFunction(arg1, arg2, x); // x not yet updated
    x = x - 1; // now finally update x
    

    So, in the case where the function is called with x--, x has effectively the same value every time the recursive function is invoked.

    Hopefully you can see from there why that produces a stack overflow