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

Siva Chelliah siva at bally.Bally.COM
Wed Sep 12 03:44:20 AEST 1990


In article <1990Aug17.164730.25750 at zip.eecs.umich.edu> huggins at zip.eecs.umich.edu (James K. Huggins) writes:
>In article <5781 at uwm.edu> 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;
>|
>|It may be a trivial question, however, is there any?  Will `y' in the first
>|conditional be tested if `x' fails?  I know that it won't in the second.
>K&R 2 specify that if 'x' fails (i.e. has value 0), 'y' will not be
>tested.
> 
>Jim Huggins, Univ. of Michigan

I was told by my teachers that this is compiler dependent.  Some compilers will
evaluate both x and y first before evaluating ( x && y).  If so, you will get
into trouble when you try to execute the following statement ( in fact this
is a neat way (?) to test how your compiler works!)
      if (x >0 && 5/x)
         statement
if x=0 , your program will crash!
I am glad that new ANSI C uses short circuiting.  
    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
I want some feed back on this if ... else stuff.  Thanks.



More information about the Comp.lang.c mailing list