简体   繁体   中英

C++ Pointer relating to NULL

I'm new to c++ and i have a question about the following code below. Is it true that the line " if(p1.spouse || p2.spouse) return false " is another way saying " if(p1.spouse!= NULL || p2.spouse!=NULL)return false " ?

struct Person     
{
    string name;       
    string bday;       
    int height;      
    Person* spouse;    
};

bool marry(Person&, Person&);

int main() 
{ 
    Person john;    
    john.name = "John";    
    john.bday = "May 29, 1917";    
    john.height = 72;    
    john.spouse = NULL;     
    Person marilyn;    
    marilyn.name = "Marilyn";        
    marilyn.bday = "06/01/1926";       
    marilyn.height = 64;        
    marilyn.spouse = NULL;    
    marry(john, marilyn); 
    cout << "John is married to " << john.spouse->name << endl;    
}

bool marry(Person& p1, Person& p2) 
{    
    if (p1.spouse || p2.spouse) return false;       
        p1.spouse = &p2;    
    p2.spouse = &p1;   
    return true;
}

Yes, it is true. Any pointer in boolean context evaluates to false if it is NULL and to true if it is not NULL.

Many people consider it poor style, and prefer to do the explicit comparison != NULL .

Personally I find it quite elegant: it means existence of the object. Particularly with short-circuit boolean && :

if (obj && ojb->whatever())
    ...;

That is true, and this is very often used feature.

from : http://en.cppreference.com/w/cpp/language/implicit_cast

"The value zero (for integral, floating-point, and unscoped enumeration) and the null pointer and the null pointer-to-member values become false. All other values become true. "

you can find a lot more implicit conversion rules at that url

Yes you're right. Any pointer ,if NULL, returns false if used in conditional expression.

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