Reputation: 3
I have come across some code along the lines of below:
if(instance != (Class*)(0))
Could someone describe what this is doing?
Upvotes: 0
Views: 402
Reputation: 18411
It short: it tests if pointer is null or not.
In detail: The expression (Class*)(0)
is actually performing a typecast from 0 (i.e. NULL
) to a pointer of type Class
, it then compares this pointer (which is a constant NULL) to the pointer variable instance
.
An example:
void Check(YourClass *instance)
{
if(instance != (YourClass*)(0))
// do this
}
Now the imporatant question is why. Why not simply as:
if(instance != 0)
// do this
Well, it is just for code-portability. Some compilers may raise warning that Class*
is being compared with int
(since NULL
is nothing but 0
, which is int
). Many static-analysis tool may also complain for simple NULL check with a class-type pointer.
Upvotes: 1
Reputation: 5760
It checks whether the pointer you're comparing it to points to NULL
. The (Class *)
cast is unnecessary. It is equivalent to the following in C++0x:
if (instance != nullptr)
Assuming that instance is a pointer, which it most certainly is.
Upvotes: 1
Reputation: 500207
If instance
is a pointer, this checks whether it is NULL
. The cast is redundant.
If instance
is something other than a pointer (e.g. an instance of some class), the semantics depend on the class because operator overloading enters the picture.
Upvotes: 1
Reputation: 258558
It checks whether instance
doesn't point to address 0
, the cast to Class*
is redundant.
If instance
is an object, it calls bool operator != (const Class*) const
;
Upvotes: 1