I have come across some code along the lines of below:
if(instance != (Class*)(0))
Could someone describe what this is doing?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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 typeClass, it then compares this pointer (which is a constant NULL) to the pointer variableinstance.An example:
Now the imporatant question is why. Why not simply as:
Well, it is just for code-portability. Some compilers may raise warning that
Class*is being compared withint(sinceNULLis nothing but0, which isint). Many static-analysis tool may also complain for simple NULL check with a class-type pointer.