Search code examples
cvariablespointersinitializationnull-pointer

Is there a difference between initialiazing variables and pointers with NULL or 0?


Which of the following methods is a more correct way to initialize a variable?

int x = 0;
int x = NULL;

What about the pointers? I have been told discordant things about NULL, like : "NULL is best for initializing pointers" or "Don't use NULL but 0 to initialize a variable" and so on... Now, I read on the internet that NULL is equal to 0 and I tested that myself. So what's the point? Why are some people saying that using NULL isn't a good choice? Is there something that I'm missing?


Solution

  • NULL is a pointer constant. You use this to initialize a pointer to a value that says it doesn't point to anything.

    On most C implementations, it is defined as:

    #define NULL ((void *)0)
    

    But there's no guarantee of that.