Home > OS >  Boolean If Statement with a Pointer to a Class
Boolean If Statement with a Pointer to a Class

Time:07-28

#define NULL 0
class Sample{
    public:
        Sample():m_nNumber(0){}
     Sample(int nNumber):m_nNumber(nNumber){}
     ~Sample(){}
     int GetNumber(){return m_nNumber;}
     void SetNumber(int nNumber){m_nNumber = nNumber;}
    private:
    int m_nNumber;
};

Sample* TestSample(Sample* mSample){
 int nNumber = mSample->GetNumber();
 if ( nNumber%2 == 0) return mSample;
 return NULL;
}


void TestNumber ( int nSample )
{
    Sample mTest(nSample);
    Sample* mTest2 = TestSample(&mTest);
    if ( mTest2 ) /* Is this statement valid? or an Undefined Behaviour? */
    {
        std::cout<<"Sample is Even"<<std::endl;
    }
    else
    {
        std::cout<<"Sample is Odd"<<std::endl;
    }
}

int main()
{
    TestNumber( 10 );
    TestNumber( 5 );
}

Given the following snippet I have a few Questions.

  1. Is it an undefined behavior to return a 0 (NULL) from a function that returns a class pointer?
  2. When doing a Boolean if statement on a pointer to a User defined class (if it's even allowed or does not result in an undefined behavior), does it evaluate the address of the pointer, or (EDIT) the value of the pointer?

I am using VS2008 due to the code I'm working on is a Legacy Source and it doesn't have updated third party Libraries.

CodePudding user response:

Both is perfectly valid and though some might argue better ways exist to handle this, still used frequently.

  • NULL is a valid value for a pointer.
  • Checking if a pointer is NULL or not is valid (that is what an if statement is doing in C , checking if the value given is not zero).

What is not "allowed" is dereferencing a NULL pointer. So any usage of it beyond checking whether it is NULL would result in some ugly behaviors.

CodePudding user response:

Is it an undefined behavior to return a 0 (NULL) from a function that returns a class pointer?

It is not undefined behavior. The literal 0 is a "null pointer constant", and it can be used to initialize a value of any pointer type.


When doing a Boolean if statement on a pointer to a User defined class (if it's even allowed or does not result in an undefined behavior), does it evaluate the address of the pointer, or the contents of the address?

if(mTest2) is a valid test. As you're not dereferencing the pionter mTest2, this checks whether the pointer is null or not and not anything about the content.


If on the other hand, you were to dereference a null pointer, then that would lead to undefined behavior.

  • Related