Are endless loops in bad form?

Posted by rlbond on Stack Overflow See other posts from Stack Overflow or by rlbond
Published on 2009-06-02T23:31:32Z Indexed on 2010/04/18 0:13 UTC
Read the original article Hit count: 580

So I have some C++ code for back-tracking nodes in a BFS algorithm. It looks a little like this:

typedef std::map<int> MapType;
bool IsValuePresent(const MapType& myMap, int beginVal, int searchVal)
{
    int current_val = beginVal;
    while (true)
    {
        if (current_val == searchVal)
            return true;

        MapType::iterator it = myMap.find(current_val);
        assert(current_val != myMap.end());
        if (current_val == it->second) // end of the line
            return false;
        current_val = it->second;
    }
}

However, the while (true) seems... suspicious to me. I know this code works, and logically I know it should work. However, I can't shake the feeling that there should be some condition in the while, but really the only possible one is to use a bool variable just to say if it's done. Should I stop worrying? Or is this really bad form.

EDIT: Thanks to all for noticing that there is a way to get around this. However, I would still like to know if there are other valid cases.

© Stack Overflow or respective owner

Related posts about c++

Related posts about coding-style