Jason Liu
Jason Liu

Reputation: 49

C++ avoid compare NULL to 0

Since in C++, NULL is essential jus 0. Every time I have a variable uninitialized set to NULL and later on I want to check whether this variable is initialized or not by comparing it to NULL. However, if the variable happens to be assigned to 0 somewhere, then there is no way I can tell whether it has been initialized or not. There is definitely some work around I can do to avoid the situation like using another wrapped object to wrap the variable or use a flag. But I am looking for a more elegant solution. For example:

int b[4] = {1,2,3,0};
int a = NULL;
int i = 0;
while(true){
    if(a == 0)return;
    a = b[i++];
}

so here it will goes into the if statement right away but I want to wait until a is assigned to 0 by b's last element

Upvotes: 1

Views: 1545

Answers (2)

Georg Schölly
Georg Schölly

Reputation: 126105

I think you're making a conceptual mistake here. Even though NULL is defined as 0 somewhere, this does not mean they are the same on a conceptual level.

NULL is a pointer with (usually) the value 0. By convention, there cannot be an object at NULL. We can therefore use code such as MyClass *obj = NULL; to specify that there is no object at obj. This works because obj is a pointer.

For non-pointer types, this does not work and we need to use other tools such as arbitrarily defining one value as invalid (often -1is used for this) or using optionals.

Upvotes: 4

Richard Hodges
Richard Hodges

Reputation: 69882

I think what you're looking for is boost::optional.

#include <boost/optional.hpp>

...

boost::optional<int> maybe_int;

...

if (maybe_int) // test if it has been assigned to
{
    if (maybe_int.value() == 0) // has is been set to zero?
    {
        // ...
    }
}    

Upvotes: 7

Related Questions