0

Why does it return 5?

#include <iostream> using namespace std; int r(int a) { if (a) return r(a + 1) + 1; else return 0; } void main() { int f = -5; cout << r(f); } I would like to know why it returns 5. I used the debugger to see how it works and once it reaches 0, automatically returns 5 and I don't understand why. Could someone explain it, please? Thanks in advance!

11th May 2018, 3:47 PM
Winter Soldier
Winter Soldier - avatar
3 Answers
+ 2
Each iteration adds 1 to the result returned. So the last iteration of the function returns 0. The second returns r(a+1) + 1. r(a+1) is 0. So it returns 1. And so on.
11th May 2018, 3:56 PM
Vlad Serbu
Vlad Serbu - avatar
+ 1
Winter Soldier the answer is in the 'r' function. It is a recursive function that will receive an int. If the int is equal to 0 (zero) it stops the recursion and return what it had until now + zero. The next recursion will add 1 to the result and to the parameter. Here is what is happening in each recursion: (imaginary result variable starts at zero) a = -5 (result) +1 a = -4 (result) +1 a = -3 (result) +1 a = -2 (result) +1 a = -1 (result) +1 a = 0 (result) +0 recursion stops ------------------------------------ total (result )=5 Hope you understand my explanation.
11th May 2018, 4:03 PM
Ulisses Cruz
Ulisses Cruz - avatar
0
I got it. Thanks a lot!
11th May 2018, 5:57 PM
Winter Soldier
Winter Soldier - avatar