When do you use "if ( a = b )"? (was Re: Funny mistake)

David Meleedy dmm at cfa.harvard.edu
Thu Mar 28 10:41:47 AEST 1991


I would like to respond to the view that statements such as
#define EQU ==
are to be avoided.

I disagree entirely.  One of the well known conventions in C is that anything
in all capital letters is defined in a define statement.  It is the
responsibility of the programmer to know to look up and see what various
defines are.  If the defined words are chosen well, this may even be
unnecessary.  The time it takes to debug a program that has 1 equal instead of
2 in an if statement does not justify the minisule effort required to understand
that EQU is equivalent to ==.  I have seen C code written with many defines
that looks just like pascal.  I do not criticize or condone this type of
programming because it is not hard to make sense out of structured and well
thought out defines.  You should not limit yourself to understanding *only* the
look of C code.  Any well structured looking algorithm should be apparent in
what it does.

if (a EQU b) {
...
}

is perfectly reasonable... in fact here is an example of some pascal type
code in c:

#include        <math.h>

#define REAL            float
#define BEGIN           {
#define WHILE           while(
#define DO              )
#define END             ;}
#define WRITELN(x)      printf("%s\n",x)
#define READ(x)         scanf("%f",&x)
#define IF              if(
#define THEN            )
#define ELSE            ;else
#define GETS            =
#define EQUALS          ==
#define NOT             !
#define WRITE(x)        printf(" %f ", x)
#define PROGRAM         main()

PROGRAM

BEGIN
                REAL    a,b,c,root1,root2,discriminant;

        a GETS 1 ;
        WHILE NOT ( a EQUALS 0 ) DO
           BEGIN
                WRITELN(" Quadratic Equation Solver.  What are a,b, and c? ");
                WRITELN(" Enter 0 alone to exit program.");
                READ( a );
                IF NOT( a EQUALS 0 ) THEN
                BEGIN
                    READ( b ) ; READ( c );
                    IF b * b - 4 * a * c < 0 THEN
                        WRITELN(" No Real Roots ")
                    ELSE
                        BEGIN
                            discriminant GETS  b * b - 4*a*c  ;
                            root1 GETS ( -b + sqrt( discriminant ) )/ 2*a ;
                            root2 GETS ( -b - sqrt( discriminant ) )/ 2*a ;
                            WRITELN(" The roots are ");
                            WRITE(root1) ; WRITE(root2) ; WRITELN("")
                        END
                END
            END
END

admittedly it's not perfect pascal, but it is certainly readable and
understandable.

_David Meleedy



More information about the Comp.lang.c mailing list