Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!iuvax!rutgers!cmcl2!adm!xadmx!fsbrn@BRL.MIL From: fsbrn@BRL.MIL (VLD/LTTB) Newsgroups: comp.lang.pascal Subject: Re: Funny evaluation of functions Message-ID: <20693@adm.BRL.MIL> Date: 23 Aug 89 20:02:51 GMT Lines: 52 Haah, Edwin J. Kay says: > The following code produces 25 as output in Turbo Pascal 4.0. Can > anyone explain what is going on? > > var y:integer; > > Function one(var x:integer):integer; > begin > x:=x+1; > one:=x; > end; > begin > y:=4; > writeln(output,y*one(y)); > end. I tried the program with Berkeley Pascal and got the same result. Pascal doesn't guarantee the order in which an expression is evaluated. What is happening is the function "one" is being called first, so "y" changes to 5, THEN the value returned by the function (also 5) is multiplied by the value of "y". 1. eval one(y) 2. change y to 5 3. return 5 4. need value of y -> get 5 5. multiply numbers together and print 25 The order of the steps *may* have been 4,1,2,3,5 giving 20. Remember that in Pascal you may not say var num [1..MAX] of integer; if (i <= MAX) AND (num[i] <> 17) because the standard says the entire expression must be evaluated, but also because it doesn't guarantee that the second expression won't be evaluated before the first one (and because Pascal doesn't terminate boolean expressions as soon as possible). This example shows why side effects are a Bad Thing. An optimizing compiler may shuffle an expression so you don't know in what order the subexpressions will be evaluated. If the program said tmp := one(y); writeln(output,y*tmp); there would be no confusion. dsw, fferd Fred S. Brundick USABRL, APG, MD.