Murzadokna
Murzadokna

Reputation: 3

Boolean Function Always Return False

It must be true but function returns false. I can't understand. How it is possible?

#include <iostream>
using namespace std;

bool Testing() {
    static int Variable = 0;

    if (Variable == 1) return true;
    else {
        Variable = 1;
        Testing();
    }

    return false;
}

int main()
{
    if (Testing()) cout << "True";
    else cout << "False";
}

image

Upvotes: 0

Views: 1791

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 598134

When main() calls Testing() for the 1st time, the static variable is created and initialized to 0. So the if evaluates to false, the variable gets updated to 1, and Testing() is called a 2nd time. And like any other function, that call will return to the place where it was called from.

Inside the 2nd Testing() run, the static initialization is skipped, and since the variable is already 1, the if evaluates as true, and so true gets returned to the caller, which is in the 1st run.

But, regardless of what that 2nd run does internally, the call site inside of the 1st run is ignoring the bool value that is returned, and so flow continues on normally, reaching the return false; statement, returning false back to the call site of the 1st run, which is in main().

bool Testing() {
    static int Variable = 0;

    if (Variable == 1)
        return true; // <-- 2nd run reaches here
    else {
                     // <-- 1st run reaches here
        Variable = 1;
        Testing();   // <-- 2nd function call made here
                     // <-- returns to here, but value is being ignored, so...
    }

    return false; // <-- 1st run reaches here, returns to main
}

To fix this, inside of Testing(), you need to change this line:

Testing();

To this instead:

return Testing();

That way, when the 2nd run returns true, the 1st run will also return true. main()will receive the finaltruethat the last recursive call toTesting()` returns.

Upvotes: 1

Related Questions