-6

For example:

node * curr;
if(curr = NULL)

vs

node * curr;
if(curr == NULL)

What do each of these things mean?

user3169700
  • 171
  • 1
  • 2
  • 12
  • 1
    The first assigns NULL to the the pointer `curr` and then tests if `curr` is non-NULL. The second tests whether `curr` is NULL. (Usually when you see a single `=` in an `if` statement it's a bug.) – Hot Licks May 31 '14 at 01:46
  • 1
    [The Definitive C++ Book Guide and List](http://stackoverflow.com/a/388282/1607442) – Ivan Aksamentov - Drop May 31 '14 at 01:46
  • Your question is missing something in a format similar to `"I know that ... means ..., but in this context .... I looked online and found ..., but ..."` – Bernhard Barker May 31 '14 at 02:49

2 Answers2

3

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.

zneak
  • 134,922
  • 42
  • 253
  • 328
0

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.

Gilbert
  • 3,740
  • 17
  • 19