Path: utzoo!utgpu!news-server.csri.toronto.edu!rutgers!cs.utexas.edu!uunet!brunix!!gvr From: gvr@cs.brown.edu (George V. Reilly) Newsgroups: comp.lang.c Subject: Re: if ( x && y ) or if ( x ) then if ( y ) ... Message-ID: <47559@brunix.UUCP> Date: 17 Aug 90 03:22:17 GMT References: <5781@uwm.edu> Sender: news@brunix.UUCP Reply-To: gvr@cs.brown.edu (George V. Reilly) Distribution: usa Organization: Brown University Department of Computer Science Lines: 34 In article <5781@uwm.edu> andrew@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@cs.brown.edu uunet!brunix!gvr gvr@browncs.bitnet Box 1910, Brown U, Prov, RI 02912