简体   繁体   中英

C++ There is a bool return type function returning (24) here

First of all sorry for too much code

Here there is a vector (teamNum) with type class, the class contain a vector (player) with type struct, it is a little complicated, but here in this function I need to check if there is a player in teamNum which contain tName equal to _tname (function parameter) contain (the player) pID equal to _pID (function parameter)

bool thereIsSimilarID(string _tname, int _pID)
{
for (int i = 0; i < teamNum.size(); i++)
{
    if (teamNum[i].tName == _tname)
    {
        for (int j = 0; j < teamNum[i].player.size(); j++)
        {
            if (teamNum[i].player[j].pID == _pID)
                return true;
        }
    }
    else if (i == (teamNum.size() - 1))
    {
        return false;
    }
}

}

And in the main

int main()
{
     cout << "\n" << thereIsSimilarID("Leverpool", 1) << endl;
}

The output is 24 !!!!! (good note that this happen just when the team (Leverpool) is the last team in the vector teamNum)

Again sorry for too much code but I need to know the bug not only fix the problem I need to learn from you

You encountered undefined behaviour.

If you take the if (teamNum[i].tName == _tname) -branch on the last element, but find no player with the correct pID, you don't return anything. Which means, that the return value is whatever random value is currently in the memory location that should hold the return value. In your case it happens to 24. But theoretically, everything could happen.

The same problem occurs when teamNum is empty.

The solution is to make sure to always return a value from a function (except if it has return type void of course):

bool thereIsSimilarID(string _tname, int _pID)
{
    for (int i = 0; i < teamNum.size(); i++)
    {
        // In this loop return true if you find a matching element
    }

    // If no matching element was found we reach this point and make sure to return a value
    return false;
}

You should take a look at your compiler settings and enable all the warnings. And often it's good to let it treat certain warnings as errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM