/*
Program: equal.c.
An example of a common, but bad bug.
*/
#include
main()
{
int n ;
/* Set n to be FALSE */
n = 0 ;
/* Error happens here. I meant to say if n is
FALSE print "My program works", but instead I
really set n to be FALSE again because I used =
(the assignment operator) instead of == for
comparison for equality. The expression (n = 0)
evaluates to 0, so instead of the condition
being TRUE, it is FALSE and the program prints
"What's wrong??"*/
if ( n = 0 )
{
printf("My program works!\n") ;
}
else
{
printf("What's wrong??\n") ;
}
}
The Sample Run
What's wrong??
The Lesson
A very common bug is using one = instead of
== to test for equality in an if statement. A
seemingly correct program can produce strange results.