I have come across some code along the lines of below:
if(instance != (Class*)(0))
Could someone describe what this is doing?
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.