3 ms·
> so unless your documentation is amazing As I pointed out I usually don't have null pointers at all. There might be a few places where a value can very obviou
by jstimpfle 9y ago
> so unless your documentation is amazing
As I pointed out I usually don't have null pointers at all. There might be a few places where a value can very obviously be null, but they are far and far between. No need for documentation.
> Boom segfault.
Which is exactly the right thing to happen (it's the C version of Exceptions in dynamic languages) since the code was incorrect.
> Always check for null. Kind of annoying and lots of people don't for whatever reason.
And now what do you do if you detected null but it was not allowed? Throw an exception? You can have that for free by just not checking.
> Use references. As you say, annoying because then you can't have null (sensibly) even when it would be really useful.
C++ references don't really protect you from NULL. It's just a different syntax for the same thing.
> Use std::optional<int&> or something like that. I only just thought of this and don't know if it would work, but I bet it's a pain.
Yes, pain, big pain. So much line noise and typing (in both senses) around what is essentially an int.
Just don't check. I don't get why there's so many places for null pointers. (As I said elsewhere, I don't have a solution for JSON style microscopic programming, and I don't care about that.).
- palunon 9y agoHow do C++ references not protect you from NULL ? From the standard: > A reference shall be initialized to refer to a valid object or function. [Note: in particular, a null reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the “object” obtained by dereferencing a null pointer, which causes undefined behavior. As described in 9.6, a reference cannot be bound directly to a bit-field. ]
- jstimpfle 9y agoBetter try instead of reading standards (and inevitably misreading, or reading differently than compiler authors)... #include <stdio.h> void test(int& x) { printf("Hello, world\n"); fflush(stdout); printf("and the number is: %d\n", x); } int main(void) { int *x = NULL; test(*x); return 0; } It's just a syntactic discipline. Null references are undefined in C++, just as NULL dereferences are undefined in C.