Calling recursive function with decreasing operator

Asked

Viewed 74 times

0

I wrote a code for solving a factor-adding problem. When I created the recursive function for the factorial calculation, I used in the function call the decrease operator -- followed by the number, and this generated an error in the answer. What is the reason for the operator to change the answer? Below is the code.

#include <iostream>
#include <cstdio>
using namespace std;

long long int factorial(long long int num){
    if(num == 1 || num == 0) return 1;
    return num*factorial(--num);
}

int main() {
    long long int M, N;
    while(scanf("%lli %lli", &M, &N)!=EOF)
        cout << factorial(M)+factorial(N) << endl;
    return 0;
}
  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site

1 answer

2

Why use this operator there? What do you expect to get out of it? It will decrement a variable that will not be used later, so it makes no sense to do this, it’s only making the code inefficient and potentially problematic since this is considered undefined behavior. This operator has the side effect of changing the state of the variable, when it occurs at a time when the variable is being used in the same expression it is not known which order will be executed each operation and everything can happen. What you want is just to take the value of the variable and subtract 1 before passing as argument to the function, do not want to change the value of that variable, then that operator does not make sense (if needed would have to do this operation in another row).

#include <iostream>
#include <cstdio>
using namespace std;

long long int factorial(long long int num) {
    if (num == 1 || num == 0) return 1;
    return num * factorial(num - 1);
}

int main() {
    long long int M, N;
    while (scanf("%lli %lli", &M, &N) != EOF) cout << factorial(M) + factorial(N) << endl;
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.