Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return true is returning 0 in C++

Tags:

c++

This is a simple recursive palindrome test that works in itself but returns 0 regardless of what the function actually returns. Here's my code, I left in debugging cout statements so you can see that it does indeed work:

bool pal(int l, int r, char *a)
{
     if(l >= r)
     {
        cout << "returning true" << endl;
        return true;
     }

     if(a[l] != a[r])
     {
        cout << "returning false" << endl;
        return false;
     }
     pal(l+1, r-1, a);
}
like image 512
Nick Sinklier Avatar asked Dec 16 '25 23:12

Nick Sinklier


2 Answers

Your program has undefined behavior because there is a path that does not return at all. You should add a return statement at the end:

return pal(l+1, r-1, a);
like image 110
Sergey Kalinichenko Avatar answered Dec 19 '25 12:12

Sergey Kalinichenko


pal(l+1, r-1, a);

That calls pal, but discards the result. It also leads to a situation in which no path returns a value (check your warnings!). What you want is:

return pal(l+1, r-1, a);
like image 21
Ed S. Avatar answered Dec 19 '25 13:12

Ed S.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!