Home > Software design >  If two functions are in arithmetic operations in recursion, which function will work first?
If two functions are in arithmetic operations in recursion, which function will work first?

Time:09-17

int count(int S[], int m, int n)
{
    if (n == 0)
        return 1;
    if (n < 0)
        return 0;
    if (m <= 0 && n >= 1)
        return 0;

    return count(S, m - 1, n)   count(S, m, n - S[m - 1]);
}

Does it end with count(S, m - 1, n) and then start with the next count(S, m, n - S[m - 1])? Or do two have to be calculators from both sides at the same time? Will there be any value change of count(S, m, n - S[m - 1]) for count(S, m - 1, n)?

Here is my full code

CodePudding user response:

See Order of evaluation

in

return count(S, m - 1, n)   count(S, m, n - S[m - 1]);

we just have the guaranty that:

  • S, m-1 (first one) and n are computed before count(S, m - 1, n)
  • m-1 (second one) is computed before S[m - 1]
  • S[m - 1] is computed before n - S[m - 1]
  • S, m, and n - S[m - 1] are computed before count(S, m, n - S[m - 1])

in particular

count(S, m - 1, n) can be computed before or after count(S, m, n - S[m - 1]) (and that for any call) (and they cannot "overlap", one is computed before the other).

Fortunately, count doesn't have side effects or change their arguments, so any order is correct in your cases.

  • Related