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

Gary Jackoway gary at hpavla.AVO.HP.COM
Sat Aug 18 00:21:22 AEST 1990


Andy asks:
> 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;

The language C guarantees "partial evaluation".  That is, if x yields 0,
y will not be evaluated at all.  That means that if y involves a function
call, the function will not be called.

So, for example, the following code is safe in C:

    if (pointer!=NULL && pointer->i == 3)

You cannot say this in Pascal, because if the pointer is NULL the 
derefence will still occur and that's not good.  (Most Pascals have a
PARTIAL_EVAL switch to allow for this.)

So the only real difference between 1 and 2 above is that you can write
an else clause on the intermediate cases:

if (x)
   if (y) s1;
   else s2;
else s3;

Note that partial evaluation also holds for the || operator as well: if 
the first operand yields non-zero, the second operand will not be evaluated.

Gary Jackoway



More information about the Comp.lang.c mailing list