Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!mailrus!cwjcc!gatech!gitpyr!gus From: gus@pyr.gatech.EDU (gus Baird) Newsgroups: comp.lang.pascal Subject: funny evaluation of functions Message-ID: <9033@pyr.gatech.EDU> Date: 23 Aug 89 18:46:08 GMT Distribution: usa Organization: Georgia Institute of Technology Lines: 48 >Article 2362 of comp.lang.pascal: >>From: edkay@lehi3b15.csee.Lehigh.EDU (Ed Kay) >Newsgroups: comp.lang.pascal >Subject: Funny evaluation of functions >Date: 23 Aug 89 15:50:10 GMT >Organization: CSEE Dept. Lehigh University, Bethlehem, PA > > 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. Huh? Why shouldn't it give 25? It looks to me like you TOLD it to... In "one", x is a variable parameter. starts at (4). gets incremented to (5) as the first op in "one". Thenceforth y of main has value (5). "one" returns the current value of (x of "one") == (y of main) = 5. Functions get evaluated first, in expression precedence rules. you get (5) back from "one(y)", multiply by (current value of y) = 5, giving 25. BTW, standard practice in Pascal shops is to not use variable parameters in functions. Usual pejorative phrase is "side effect". -- gus Baird School of ICS, Georgia Institute of Technology, Atlanta, Georgia, 30332 ...!{decvax,hplabs,ncar,purdue,rutgers}!gatech!gitpyr!gus