Confusing Assignment and Equality Operators

A common error is to confuse the assignment operator (=) with the equality operator (==). The mistake often occurs in decision-making statements:

int val = 555;

if( val = 20 )/* Error! */

printf( "val equals 20\n" );

The above code prints val equals 20 even though it's clear val doesn't equal 20 when the if statement begins. Instead of testing whether x equals 20, the expression val = 20 assigns the value 20 to val.

Remember, the single equal sign (=) performs an assignment in C. This particular assignment results in a nonzero value, so the if test is evaluated as true, causing the printf statement to execute.

To correct the problem, use the double equal sign (==) to test equality:

if( x == 20 )

printf( "x equals 20\n" );

Once you're in the habit of using the equality operator, you might make the opposite mistake of using two equal signs where you should use only one:

main()

{

int val;

for( val == 0; val < 5; val++ ) /* Error! */

printf( "val = %d\n", val );

}

Here the error appears in the initializing expression of the for statement. It's the reverse of what happened in the first example. Instead of assigning the value 0 to val, the expression val == 0 evaluates whether or not val equals 0. The expression doesn't change the value of val at all. Since val is an uninitialized variable, the for loop is unpredictable.