rasayani said:
Does anyone know what the advantage is of using the following statement
char *p = NULL;
if (NULL == p)
{
}
over
char *p = NULL;
if (p == NULL)
{
}
If you mistakenly type
if (p = NULL) {...}
then p will be assigned NULL instead of compared against null, and the
branch will never be taken, which is a bug. On the other hand, if you
mistakenly type
if (NULL = p) {...}
you will raise a diagnostic at compile time, since NULL cannot be assigned
to. So the NULL == p form is a good way to catch a certain class of typo,
but only in cases where one of the operands is not an lvalue.
For this *specific* instance, you can avoid the headache completely by
typing
if (!p) {...}
since !p is equivalent to p == NULL.
It would have been nice if dmr had realized early on that allowing
assignment expressions in conditionals could lead to problems, or if he had
used a different operator for assignment or equality (i.e., := and ==, or =
and :=, or something where the two operators don't start with the same
character). But he didn't, and we're stuck with the consequences.