-1

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;
}
4
  • format your code please Commented Nov 5, 2014 at 19:00
  • why don't you run the code a few times, and analyze what happens Commented Nov 5, 2014 at 19:02
  • 5
    @SamIam: That is a double-edged advice! While it is useful to see what happens, imagine if the question is: "is it true that uninitialized local variables are automatically set to 0?".
    – rodrigo
    Commented Nov 5, 2014 at 19:04
  • @rodrigo: Thank you for understanding where i'm coming from!
    – Ryan
    Commented Nov 5, 2014 at 19:05

3 Answers 3

3

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())
    ...;
1

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

2
  • @MooingDuck agree, for floating points always use epsilon if-s
    – marcinj
    Commented Nov 5, 2014 at 19:06
  • @MooingDuck Unless you know they are exactly the value they should be. Which they seldom enough are. Commented Nov 5, 2014 at 19:07
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.