简体   繁体   中英

Cannot use int post-decrement in function call

I made a recursive exponential function and originally called the recursive function as return num * power(num, exp--) , however I had to change it to exp-1 because the first method broke the program. Why do I have to use exp-1 ?

#include <iostream>
using namespace std;

int power(int num, int exp);

int main()
{
    cout << power(5, 3) << endl;

    return 0;
}

int power(int num, int exp)
{
    if (exp == 0)
        return 1;
    else
        return num * power(num, exp-1);
}

That's because, exp-- firstly uses your value for invoking power() function and then gets decremented. In that case, the value passed to the function remains 3. Therefore, it goes into the infinite loop.

You should use either --exp or exp-1 .

You need --exp , not exp-- . exp-- is post-decrement, meaning that it will only be executed after the function call. So, exp-- is not equivalent to exp-1 in your code, but --exp is: the value will be decremented first, and then the function will be called with the decremented value.

Why do I have to use exp-1?

You could also pre-increment --exp which gives you the incremented value.

Post-increment exp-- takes current value and decrements afterwards.
In your case that never changes the value.

You take current the value of exp and you're passing it by value to function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM