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

George V. Reilly gvr at cs.brown.edu
Fri Aug 17 13:22:17 AEST 1990


In article <5781 at uwm.edu> andrew at csd4.csd.uwm.edu (Andy Biewer) writes:
% Much of the time during programming in C I run into the same question about
% conditional statements such as the subject.  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.
% 
% Because it's a conjunction, logically it is unnecessary to test `y' because
% the whole evaluation is false if `x' fails.  And, of course, with a
% disjunction it would be necessary to test `y'.  But, is the compiler smart
% enough to take these facts into consideration (or is it even possible to)?

Yes, not only is it smart enough to, but it is required to.  From K&R2, p. 21,
	"Expressions connected by && and || are evaluated left to right,
	 and it is guaranteed that evaluation will stop as soon as the
	 truth or falsehood is known."

This is also known as short-circuiting Boolean expressions.

[I wonder how many people will jump in and post followups to Andy's
 question without checking to see if anybody else has done so.  Just
 hope I don't end up with egg on my face for making this remark.]
________________
George V. Reilly			gvr at cs.brown.edu
uunet!brunix!gvr   gvr at browncs.bitnet	Box 1910, Brown U, Prov, RI 02912



More information about the Comp.lang.c mailing list