Can I use NULL as substitution for the value of 0?

2020-02-20 07:34发布

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.

7条回答
Anthone
2楼-- · 2020-02-20 07:56

Disclaimer: I don't know C++. My answer is not meant to be applied in the context of C++

'\0' is an int with value zero, just 100% exactly like 0.

for (int k = 10; k > '\0'; k--) /* void */;
for (int k = 10; k > 0; k--) /* void */;

In the context of pointers, 0 and NULL are 100% equivalent:

if (ptr) /* ... */;
if (ptr != NULL) /* ... */;
if (ptr != '\0') /* ... */;
if (ptr != 0) /* ... */;

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). In ptr + NULL if either ptr or NULL is a pointer, the other must be an integer, so ptr + NULL is effectively (int)ptr + NULL or ptr + (int)NULL and depending on the definitions of ptr and NULL several behaviours can be expected: it all working, warning for conversion between pointer and integer, failure to compile, ...

查看更多
登录 后发表回答