Hacker News new | ask | show | jobs
by JeremyStein 6066 days ago
!ptr is bad.

I worked with a C programmer who changed all occurrences of "ptr != 0" to "!ptr". The program stopped working. In Windows, a null pointer is not 0. The C idiom "ptr != 0" compiles correctly, but when you try to get clever with "!ptr", you were in trouble. The expression would evaluate to false on a null pointer. (At least with the version of Visual C++ we were using back then.)

2 comments

This was true years ago (and may be true still if you have to support legacy or niche compilers) but in current standard C and C++, the null pointer is guaranteed to equal zero in integer comparisons (and therefore false in boolean expressions).

http://www.research.att.com/~bs/bs_faq2.html#null

http://www.faqs.org/faqs/C-faq/faq/

> the null pointer is guaranteed to equal zero in integer comparisons (and therefore false in boolean expressions).

Note that this does not mean that the null pointer is 0.

I'll quote the relevant sentence from section 5.2 of http://www.faqs.org/faqs/C-faq/faq/: "According to the language definition, a constant 0 in a pointer context is converted into a null pointer at compile time."

Later in that section, there's an example that makes the difference between "null pointers are 0" and "constant 0s in a pointer context are converted into a null pointer". The intro to that example is "However, an argument being passed to a function is not necessarily recognizable as a pointer context, and the compiler may not be able to tell that an unadorned 0 "means" a null pointer. To generate a null pointer in a function call context, an explicit cast may be required, to force the 0 to be recognized as a pointer."

The example itself is: "execl("/bin/sh", "sh", "-c", "date", (char )0); If the (char ) cast on the last argument were omitted, the compiler would not know to pass a null pointer, and would pass an integer 0 instead."

See also 5.3 which starts with "Is the abbreviated pointer comparison "if(p)" to test for non- null pointers valid? What if the internal representation for null pointers is nonzero?"

The change reverses the logic of the expression, so I would expect the program to stop working - regardless of the value of the null pointer.
Bah. You're right. I meant ptr == 0 was changed to !ptr.