Re:The Ten Commandments for C Programmers (1987)
by monocasa on Saturday May 23, 2020 @01:39PM
(#23284829)
It'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
Re:The Ten Commandments for C Programmers (1987)
by a1369209993 on Wednesday May 27, 2020 @10:37PM
(#23332809)
Much, 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*.
Re:The Ten Commandments for C Programmers (1987)
by microtherion on Saturday May 23, 2020 @01:51PM
(#23284930)
You'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.
Re:The Ten Commandments for C Programmers (1987)
by verall on Sunday May 24, 2020 @12:05PM
(#23292440)
> 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)
Re:The Ten Commandments for C Programmers (1987)
by eMSF on Sunday May 24, 2020 @03:52PM
(#23294191)
Yes. 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.)
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.)