My question title could be improved, if there's a specific name for what I will talk about let me know.
This isn't for a specific language either, all the ones I've used treat function calls as expressions the same.
So I've been reading about recursion and tail calls, so I wrote this code in C++
#include <iostream>
using std::cout;
int test(int num) {
if (num > 0) {
return test(num - 1);
}
}
int fact(int num) {
return num == 0 ? 1 : num*fact(num - 1);
}
int main() {
cout << test(20) << '\n';
return 0;
}
Of course test(num)
would always evaluate to 0
if num > 0
, since base case is n = 0
.
But why? How does the language know what should be returned? How does it know what test(n - 1)
should evaluate to?
Edit;
I've included a recursive method of getting the factorial of a number. How would C++ (or any language) know what to multiply num
by?