Search code examples
c++vectornullreturn-valuefunction-definition

What if I need to differentiate 0 from NULL in C++?


** Please don't criticize the purpose of the code itself. It's from Pat Morin's Open Data Structures book. Not my first choice, its assigned reading/practice. I just wanted to know if there is a way to differentiate, or a better way to go about this. Textbook--> http://opendatastructures.org/ods-cpp/**

** Another note: I'm coming from Java, where this would be allowed. My code still compiles, it just "fixes" it**

I'm surprised nothing like this has come up before because it seems like such a simple question. Perhaps it's buried or I'm not using the correct terminology.

I have a for loop that goes through the data in a vector. I need to return the value being searched for if it's found. What if it's not found? Here is my code.

int find(int x) {
    for(int i=0;i<bag.size();i++){
        // if x is equal to data, return data
        if (bag[i]==x){
            return bag[i]; // ends loop as soon as one instance is found
        }
    }
    // if we made it this far, no match was found.
    return NULL;

}

Pretty simple. Let's say 0 is one of the valid values that I might need to record and search for. As it is, it actually returns 0, not "NULL". Research says it is one and the same. How can I specify or differentiate? Other than returning an obsqure number that won't come up in the program because we may not always have that luxury (like -1 or -9999999). For example, searching for your account balance. No number is impossible.


Solution

  • You can write the function in several ways

    bool find( int x ) 
    {
        std::vector<int>::size_type i = 0;
    
        while (  i < bag.size() && bag[i] != x ) i++;
    
        return i != bag.size();
    }
    

    Or

    std::vector<int>::size_type find( int x ) 
    {
        std::vector<int>::size_type i = 0;
    
        while (  i < bag.size() && bag[i] != x ) i++;
    
        return i;
    }
    

    Or

    #include <algorithm>
    
    //...
    
    std::vector<int>::iterator find( int x ) 
    {
        return std::find( beg.begin(), bag.end(), x );
    }
    

    And use the functions correspondingly the following ways

    if ( find( x ) ) { /*...*/ }
    
    if ( find( x ) != bag.size() ) { /*...*/ }
    
    if ( find( x ) != bag.end() ) { /*...*/ }
    

    As for your general question in the title of the post

    What if I need to differentiate 0 from NULL in C++?

    then you need fo use nullptr instead of NULL that to differentiate 0 from NULL.:)