if ( x && y ) or if ( x ) then if ( y ) ...

David Brooks dbrooks at osf.org
Wed Sep 12 05:12:01 AEST 1990


In article <367 at bally.Bally.COM>, siva at bally.Bally.COM (Siva Chelliah) writes:
|> I was told by my teachers that this is compiler dependent.  Some
compilers will
|> evaluate both x and y first before evaluating ( x && y).

Your next step is to go to this teacher and demand your tuition fees
back.  One of three possible explanations:

- The teacher doesn't know what s/he is talking about.

- The teacher has seen a compiler with this behavior and didn't
  properly explain that it is broken and should be avoided at all
  costs.  It will fail to compile thousands of correct programs.

- The teacher was talking about some other language, not C, and didn't
  detect you in the wrong class.

Strictly, your second sentence should say "Some compilers will
produce code that will evaluate..."

|>     Furthermore, I read somewhere that you should not use if ... then
if 
|> (under structured programming principles I guess), so the following
stmt : 
|>         if (x)
|>            if (y)
|>               statement1
|>            else
|>               statement2
|>         else
|>            statement3
|> 
|> should  be re-written as
|>           if (!x)
|>              statement3
|>           else if (y)
|>                   statement1
|>                else
|>                   statement2

You are probably thinking of the "dangling else", which some of us
first met in Algol 60.  The ambiguity lies in this:

        if (x)
           if (y)
              statement1
           else
              statement2

Since compilers don't read formatting, which "if" owns the "else"?
The C answer is "by associating the "else" with the closest previous
"else"-less "if". (K&R2, p56), which is the decision implied by the
formatting above.  Your example is not ambiguous, but I would put some
redundant braces in it (no flames about that, please).

Do I detect the resumption of classes?
-- 
David Brooks				dbrooks at osf.org
Systems Engineering, OSF		uunet!osf.org!dbrooks
Experience Hackvergnuegen!



More information about the Comp.lang.c mailing list