Am I allowed to use the NULL
pointer as replacement for the value of 0
?
Or is there anything wrong about that doing?
Like, for example:
int i = NULL;
as replacement for:
int i = 0;
As experiment I compiled the following code:
#include <stdio.h>
int main(void)
{
int i = NULL;
printf("%d",i);
return 0;
}
Output:
0
Indeed it gives me this warning, which is completely correct on its own:
warning: initialization makes integer from pointer without a cast [-Wint-conversion]
but the result is still equivalent.
- Am I crossing into "Undefined Behavior" with this?
- Is it permissible to utilize
NULL
in this way? - Is there anything wrong with using
NULL
as a numerical value in arithmetical expressions? - And what is the result and behavior in C++ for this case?
I have read the answers of What is the difference between NULL, '\0' and 0 about what the difference between NULL
, \0
and 0
is, but I did not get the concise information from there, if it is quite permissible and also right to use NULL
as value to operate with in assignments and other arithmetical operations.
Disclaimer: I don't know C++. My answer is not meant to be applied in the context of C++
'\0'
is anint
with value zero, just 100% exactly like0
.In the context of pointers,
0
andNULL
are 100% equivalent:are all 100% equivalent.
Note about
ptr + NULL
The context of
ptr + NULL
is not that of pointers. There is no definition for the addition of pointers in the C language; pointers and integers can be added (or subtracted). Inptr + NULL
if eitherptr
orNULL
is a pointer, the other must be an integer, soptr + NULL
is effectively(int)ptr + NULL
orptr + (int)NULL
and depending on the definitions ofptr
andNULL
several behaviours can be expected: it all working, warning for conversion between pointer and integer, failure to compile, ...