#include <stdio.h>
int main(){
int *p = '\0';
if (p == NULL){
// this block will get executed.
}
return 0;
}
I have read that 0
, NULL
and \0
are all equal to the integer constant 0
in C.
So is the above code technically correct in setting and checking for a NULL pointer? I guess it still needs to be avoided as \0
is mainly used to terminate strings and its usage here is confusing?
'\0'
is an integer zero.
All three do exactly the same.
int *p = NULL;
int *p = 0;
int *p = '\0';
but the last two may emit the warning.
The best way to describe is that a pointer can be a zero, indicating its functionally pointing to nothing (which isn't true: it's actually pointing at memory spot zero). But there are many ways to represent a zero, and NULL
is one of those ways. So technically, any way you write the zero is technically legally as long as the compiler interprets it as "zero".
FYI, some people write if
statements in reverse to protect against an accidental assignment if you forget an equal sign:
if (NULL == p){
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With