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

Mostly Harmless jdarcy at encore.com
Fri Aug 17 22:58:48 AEST 1990


andrew at csd4.csd.uwm.edu (Andy Biewer) writes:
>I have been wondering for quite
>some time now about what, if any, differences there are between the two
>conditional statements:
>
>  1)  if ( x && y )
>          statement;
>
>  2)  if ( x )
>          if ( y )
>               statement;

I can't say whether or not this is standard behaviour, but all of the compilers
I've worked with will use "short-circuited evaluation" for the first construct.
In other words, condition "y" will NOT be evaluated if condition "x" is false.

The major difference between the two forms is the meaning of an "else" after
each.  Don't laugh; I've seen dozens or possibly hundreds of bugs caused by
this and similar logic errors.  In the first form, an else will be executed
if (!x || !y), whereas in the second it will be executed if (x && !y).  Even
if you put braces around the second "if", an else will only be executed when
(!x).

--

Jeff d'Arcy, Generic Software Engineer - jdarcy at encore.com
      Nothing was ever achieved by accepting reality



More information about the Comp.lang.c mailing list