Is it safe to assume that NULL
always translates to false in C?
void *somePtr = NULL;
if (!somePtr) {
/* This will always be executed? */
}
Or should an explicit check against the value of NULL
be made?
Is it safe to assume that NULL
always translates to false in C?
void *somePtr = NULL;
if (!somePtr) {
/* This will always be executed? */
}
Or should an explicit check against the value of NULL
be made?
Yes (at least for any standards compliant C compiler!)
From the comp.lang.c FAQ:
Yes,
if(!p)
is valid and guaranteed to work.https://port70.net/~nsz/c/c11/n1570.html#6.3.2.3p3
This means that
(void*)0
is a null pointer. It also means that ifp
is a pointer, thenp==0
is equivalent top==(void*)0
.It also means that if
p
is a not a null pointer, thenp==(void*)0
will evaluate to0
.So far, so good.
http://port70.net/~nsz/c/c11/n1570.html#6.3.2.3p4
Note that "Any two null pointers shall compare equal." This means that if
p
is a null pointer, thenp==0
will evaluate to true, because0
will be promoted to(void*)0
which is a null pointer. It also mean that no non-null pointer can be equal to a null pointer.Let's have a look at the negation operator.
http://port70.net/~nsz/c/c11/n1570.html#6.5.3.3p5
This tells us that
!p
is the same asp==0
by definition, which is the same asp==(void*)0
as mentioned above.And taking the fact that all null pointers are equal into consideration, this means that
p==(void*)0
can only evaluate to true ifp
is a null pointer and and only false ifp
is not a null pointer.So yes,
if(!p)
is a perfectly safe way to check ifp
is a null pointer or not.NULL
is defined as a constant pointer that is guaranteed to point to a useless/non-existent place in memory. Most implementations ofNULL
are((void *)0)
but it is not mandatory that this is so.Yes it:
C standard 6.3.2.3
and 6.3.2.6
-
It's never safe to assume anything.
An explicit check is also more clear about what you're testing.
What is NULL?
What is the value of the null pointer constant?
Example Definition:
Evaluating if(NULL)
So yes if the compiler is compliant with ISO C99 you can assume that the statement below will always execute.
Above quotations are from ISO/IEC 9899:1999 (C99). You can read it here.