I made a recursive C++ program that looks like this:
using namespace std;
#include <iostream>
bool recursive(int num)
{
if (num == 6)
{
return false;
}
else if (num > 6)
{
return true;
}
else
{
if (recursive(num + 1))
{
return true;
}
else
{
return false;
}
}
}
int main()
{
if (recursive(0))
{
cout << "Not found!" << endl;
}
else
{
cout << "Found..." << endl;
}
}
It works and I assumed that this was (roughly) the best way to do it.
My friend made a simpler recursive program that looks like this:
using namespace std;
#include <iostream>
bool recursive(int num)
{
if (num == 6)
{
return false;
}
else if (num > 6)
{
return true;
}
else
{
recursive(num + 1);
}
}
int main()
{
if (recursive(0))
{
cout << "Not found!" << endl;
}
else
{
cout << "Found..." << endl;
}
}
His works just like mine does, but I don't understand why it works. To me, it looks like nothing gets returned in his else block, so I don't understand how the boolean value gets returned to the original function call.
Out of curiosity, I made a similar program in JavaScript:
function recursive(index)
{
if (index == 6)
{
return true;
}
else if (index > 6)
{
return false;
}
else
{
recursive(index + 1);
}
}
if (recursive(0))
{
console.log("found");
}
else
{
console.log("not found");
}
But the JavaScript program doesn't work, which makes me think that this is specific to C++.
Why does my friend's program work? Is it completely valid, or is it undefined behavior?