by hy3lxs · 17y ago · 0 comments
if (ptr) {
ptr->foo();
} else {
die();
}
or if (!ptr) {
OhNoes();
}
Also, you can extend the whole lhs-rvalue thing to for loops. Makes them look funny but you get used to it quickly, especially after it helps you avoid a few bugs. for (i = v.begin(); v.end() != i; ++i) {
i->stuff();
}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.)
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?"