Path: utzoo!utgpu!water!watmath!clyde!rutgers!ucla-cs!cit-vax!elroy!ames!umd5!uvaarpa!virginia!scl From: scl@virginia.acc.virginia.edu (Steve Losen) Newsgroups: comp.lang.pascal Subject: Re: Pascal User Manual and Report Keywords: side effects Message-ID: <588@virginia.acc.virginia.edu> Date: 19 Feb 88 16:16:20 GMT References: <11899@brl-adm.ARPA> Reply-To: scl@virginia.acc.Virginia.EDU (Steve Losen) Organization: University of Va., Charlottesville, VA Lines: 77 Side effects should be avoided at all costs! In article <11899@brl-adm.ARPA> wsmith@b.cs.uiuc.EDU writes: >program side; > var x:integer; >function side_effect:boolean; >begin > x:=1; > side_effect:=true >end; >begin > termout(output); > x:=2; > if (x<2) and side_effect > then writeln(True,x) else writeln(False,x); > x:=2; > if (x<3) and side_effect > then writeln(True,x) else writeln(False,x); >end. > > >>What if the second part of the AND expression has side effects? If my >>reading of Jensen & Wirth is correct, the result of any program with such >>side effects is undefined in Pascal! Is this conclusion true? It certainly >>isn't a pleasant one since there is probably plenty of code that depends on >>the evaluation of the second part being required. > >I suppose that this program would have different results via your compiler. There are lots of little gotchas waiting for the unsuspecting programmer who uses side effects. CAVEAT 1: The order of evaluation of procedure and function parameters is implementation depended in pascal. Consider the following: x:=5; foo(x, side_effect); Some pascal compilers may evaluate x first, some may evaluate side_effect first, so depending on the compiler you could be doing foo(5,true) or foo(1,true). CAVEAT 2: The order of the evaluation of the operands of a dyadic operator is implementation dependent in pascal. Suppose side_effect returns an integer: function side_effect: integer begin x := 1; side_effect := 3; end; x := 5; y := x + side_effect; Some pascal compilers will evaluate x first and some will evaluate side_effect first, so y could be either 8 or 4. Note also that "and" and "or" are also dyadic operators. Furthermore, pascal does not require that both operands to "and" and "or" be evaluated. Thus, booleexpr1 and booleexpr2 could be evaluated left to right, right to left, left side only, or right side only, depending on the compiler and the values of the expressions. These sorts of traps are much easier for C programmers like myself to fall into because side effects are much easier to generate. In this C example, z could be 10 or 15 depending on the compiler. x = 10; z = (x = 5) + x; -- Steve Losen scl@virginia.edu University of Virginia Academic Computing Center