1

In C++ I have commonly seen code that look something like this:

Object * p = init();
if (!p) {
    printf("Fail");
}
else {
    printf("Success");
}

As far as I can tell, it's checking to see if 'p' has been initialized correctly. We can achieve a similar result without the ! operator with the following if statements:

Object * p = init();
if (p) {
    printf("Success");
}
else {
    printf("Fail");
}

I've never actually read anywhere why this is done. I just know that it works. I know that conditionals in C++ can contain bools or integers where 0 is false and everything else is true, but how does it work with objects? I'm guessing maybe it has something to do with null pointers, but I've never seen it explicitly mentioned anywhere before.

user3567004
  • 117
  • 1
  • 12
  • Note that any integer, and we can lump in pointers for this case, is considered false for 0 and true for any other number. Your code above takes advantage of this. – user4581301 Aug 27 '18 at 21:33
  • To expound on user4581301's comment, the null pointer is always equivalent to the integer zero. Any other pointer has an unspecified value, but a pointer is always zero iff null. – Silvio Mayolo Aug 27 '18 at 21:35
  • 2
    I think an important note here is that `p` is not an object. It is a pointer. It doesn't matter what it is pointing at, or if there is any object that was initialized correctly or not. If the pointer is pointing at something, it is not null, therefore it evaluates to true. This however does not guarantee that whatever the pointer is pointing at is valid memory or a valid object or a valid whatever. You can have dangling pointers, e.g. after the memory has been freed. Such a pointer would still evaluate to true, even though accessing it would be illegal and possibly cause a crash. – Max Vollmer Aug 27 '18 at 21:39
  • @MaxVollmer pointers are objects. Also, doing `!p` after `delete p;` causes implementation-defined behaviour (which may include aborting the program) – M.M Aug 28 '18 at 01:24
  • @SilvioMayolo it's not true that "any other pointer has an unspecified value" , and a null pointer may be *tested for equality* with `0` but that's where the "equivalence" ends – M.M Aug 28 '18 at 01:26

0 Answers0