For example:
node * curr;
if(curr = NULL)
vs
node * curr;
if(curr == NULL)
What do each of these things mean?
For example:
node * curr;
if(curr = NULL)
vs
node * curr;
if(curr == NULL)
What do each of these things mean?
Yes, they are different.
The first example uses the assignment operator (=
) and assigns NULL
tocurr
, and then its value is used as the condition for the if
. Since it's NULL
, and NULL
is considered false when it comes to conditions, execution will never enter the block. This is most likely a bug and at least GCC and Clang will emit a warning for it.
The second one uses the comparison operator (==
) to compare curr
to NULL
. If curr
is equal to NULL
, execution will enter the block. curr
remains unchanged.
In any C language, or many derived from C, a single = is assignment and double == is equality test.
if ( curr = NULL )
assigns NULL to curr then tests if true or false. It is always false.
if ( curr == NULL)
tests if curr is NULL and does not change it.
As it is all too easy to drop an "=" converting equality tests to an assignment I have started putting the constant on the left: NULL == curr
. If I ever drop an equal it becomes NULL = curr
, which is invalid and the compiler throws a fatal error. Yes, high compiler checks can catch such drops, but my way guarantees compiler failures.