Search code examples
c++nullreturnutility

How to return nullptr equivalent from a C++ function whose return type is pair?


pair<int, int> findEmpty(int bo[9][9], int n){
    for(int i=0;i<n;i++){
        for(int j=0;j<n;j++){
            if(bo[i][j]==0){
                return (make_pair(i, j));
            }
        }
    }
    //return nullptr; 
}

If nullptr can't be returned, what are the alternatives?


Solution

  • Use an optional<T> type to represent potentially non-existent state.

    If you're using C++17 this can be done with std::optional<T>, if you use Boost then boost::optional<T>, etc. You can even implement your own version of optional. The point is to use a semantic type that indicates that there may, or may not, be a value.

    Using std::optional from C++17, your code becomes:

    optional<pair<int, int>> findEmpty(int bo[9][9], int n){
        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++){
                if(bo[i][j]==0){
                    return make_pair(i, j);
                }
            }
        }
        return nullopt; 
    }
    

    Although you could solve this by returning sentinel-like values such as a pair of (-1, -1), this is not a recommended practice. This forces checking for specific sentinel values on the caller, which can easily be missed or forgotten -- and may cause the bad sentinel value to find its way into other arithmetic or indirections that may never expect a negative value.

    Using a semantic type to convey the nullability helps to prevent these sorts of errors.