Re:C++ Annotations
by cjs_2 on Saturday November 24, 2018 @02:09AM
(#18520882)
What would you suggest using instead? The actual (void *) 0?
[ Parent
| on HN ]
Re:C++ Annotations
by CopperWing on Saturday November 24, 2018 @02:17AM
(#18520902)
In C++, nullptr.
And in C?
Re:C++ Annotations
by craigching on Saturday November 24, 2018 @03:02AM
(#18521017)
In C, always use 0 and check for 0, it's the only safe way. For C++, it depends on the standard you're using.
Except when calling a varargs function, when you need to cast to the correct pointer type
But 0 isn't always null right?
Literal zero in a pointer context is interpreted by the compiler to mean "the null pointer." The compiler then compiles the null pointer into the code.
But then how do you get a pointer to zero (not null) in those systems?
First, that's inherently non-portable. That aside...
On most systems, the null pointer happens to be a pointer to address zero. For other systems, e.g. 8086 16-bit mode, you can create a intptr_t (which is the same size as a pointer) and set it to zero. Then cast it to a pointer. Such casting is always done bitwise, so it will work.
The compiler knows to turn the following into the null pointer
void *p = (void *) 0;
but the compiler will NOT turn the following into a null pointer void *p = (void *) (uintptr_t) 0;
because the literal 0 is now in an integer context, not a pointer context.BTW 0 is a valid literal value of a pointer type (so you do not need a cast).
Thank you!
Prior to nullptr, generally I used literal 0. In those cases which require disambiguation, I used (void * ) 0.