== vs =

The Program

/***************************************** Program: equal.c. Author: New C programmers Date: Every semester Section: All sections Email: everyone@umbc.edu An example of a common, but bad bug. *****************************************/ #include <stdio.h> int 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") ; } return 0; }

The Sample Run

What's wrong??

The Lesson

Salvation !!

Most newer compilers (including ours at UMBC) will report a warning message if you use '=' in an if statement.

linux1[108] % gcc -Wall -ansi equal.c
equal.c: In function `main':
equal.c:28: warning: suggest parentheses around assignment used as truth value
linux1[109] %