Node:Confusion of = and ==, Next:, Previous:Run-time errors, Up:Run-time errors



Confusion of = and ==

Consider the following program:

#include <stdio.h>

/* To shorten example, not using argp */
int main()
{
  int my_int = 0;

  if (my_int = 1)
    {
      printf ("Hello!\n");
    }

  return 0;
}

What will this program do? If you guessed that it will print Hello!, you are correct. The assignment operator (=) was used by mistake instead of the equality operator (==). What is being tested in the above if statement is not whether my_int has a value of 1 (which would be written if my_int == 1), but instead what the value is of the assignment statement my_int = 1. Since the value of an assignment statement is always the result of the assignment, and my_int is here being assigned a value of 1, the result is 1, which C considers to be equivalent to TRUE. Thus, the program prints out its greeting.

Even the best C programmers make this mistake from time to time, and tracking down an error like this can be maddening. Using the -Wall option of GCC can help at least a little by giving you a warning like the following:

equals.c: In function `main':
equals.c:7: warning: suggest parentheses around assignment used as truth value