UMBC CS 201, Spring 02
UMBC CMSC 201 Spring '02 CSEE | 201 | 201 S'02 | lectures | news | help

== vs =

The Program

/***************************************** Program: equal.c. Author: A new C programmer Date: Every semester 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 a 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] %


CSEE | 201 | 201 S'02 | lectures | news | help

Thursday, 17-Jan-2002 13:52:01 EST