0

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?

incapaz
  • 349
  • 1
  • 3
  • 11
  • It actually doesn't because you haven't said what to return when `num <= 0` so in fact the result of this function should be undefined. Basically, you have written buggy and incomplete code. Does this even compile? Do you not get any warnings at all? – Lasse V. Karlsen Jul 01 '19 at 07:56
  • @LasseVågsætherKarlsen no not at all. I've tested this on JavaScript, Java, Lua and Python (changing the syntax ofc) and I still get 0 – incapaz Jul 01 '19 at 08:04
  • Some programming languages will default to 0, None, nil, null, etc. when you don't have an explicit return statement, not sure about C though. – Lasse V. Karlsen Jul 01 '19 at 08:43

0 Answers0