4 ms·
>* Casting NULL is pointless, as it's already defined by the standard to be a pointer constant, compatible with all data pointers. You should still cast NULL w
by eMSF 6y ago
>* Casting NULL is pointless, as it's already defined by the standard to be a pointer constant, compatible with all data pointers.
You should still cast NULL when passed as an unnamed argument to a variadic function. While NULL is defined to be a null pointer constant, that doesn't mean it has a pointer type (all integer literals with a value of zero are null pointer constants in C, but they have an integer type).
(Strictly speaking, all unnamed pointer arguments to variadic functions should be converted to a compatible pointer type that the variadic function expects. For example, the printf-line of functions expect a pointer-to-void argument for a conversion specifier %p. If you pass a pointer-to-int instead, technically the behaviour is undefined.)
(To whom it may concern: I would appreciate at least a rebuttal. It's not like this is a subjective matter.)
- monocasa 6y agoIt's unfortunate that you're getting downvoted; there's for sure real dragons at the intersection of the NULL literal and variadic functions since it's totally legal for NULL to be defined as such: #define NULL 0
- a1369209993 6y agoMuch, much more subtly nasty, it's also legal for NULL to be defined as: #define NULL ((void*)0) and then passed to a function that expects variadic int* parameters on a machine where register-sized addresses are word-aligned and thus int* has a different sizeof (and/or bit-level representation) than void*.
- microtherion 6y agoYou're right, I was misinterpreting the language of the standard. As a practical matter, C implementations typically define NULL as a void pointer, so the cast is not necessary in those implementations (In C++ pre C++11, NULL is always defined as a literal 0, so the cast is definitely necessary). But it appears the standard allows C implementations to define NULL as a literal 0 or as 0L as well, so the cast is needed in portable code.
- verall 6y ago> If you pass a pointer-to-int instead, technically the behaviour is undefined. But if you cast the intptr to voidptr, the behavior is defined, right? (Besides that %p is nonstandard iirc)
- eMSF 6y agoYes. Also, %p isn't non-standard, however the conversion is implementation-defined. (The reason why I used the word technically earlier was because on all common platforms int-pointers and void-pointers – and indeed all object pointers – have identical binary representation.)