Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!mailrus!tut.cis.ohio-state.edu!gem.mps.ohio-state.edu!rpi!pawl24.pawl.rpi.edu!mketch From: mketch@pawl.rpi.edu (Michael D. Ketchen) Newsgroups: comp.lang.pascal Subject: Re: Funny evaluation of functions Keywords: functions, precedence Message-ID: <6898@rpi.edu> Date: 23 Aug 89 18:23:40 GMT References: <614@lehi3b15.csee.Lehigh.EDU> Sender: usenet@rpi.edu Organization: Rensselaer Polytechnic Institute, Troy, NY Lines: 45 In article <614@lehi3b15.csee.Lehigh.EDU> edkay@lehi3b15.csee.Lehigh.EDU (Ed Kay) writes: > > The following code produces 25 as output in Turbo Pascal 4.0. Can >anyone explain what is going on? Well, I'll try... > var y:integer; > > Function one(var x:integer):integer; > begin > x:=x+1; > one:=x; > end; > begin > y:=4; > writeln(output,y*one(y)); Okay, when the compiler sees the expression "y*one(y)", it builds code to evaluate it. Now, from the output you gave (25), it appears that the 'y' portion is stored as a pointer to y's variable location in memory. Since the parameter of one() is call-by-reference and is changed in the function, y's value in memory is also changed. Note that this is BEFORE the actual evaluation of the expression. So, you start with y=4. The expression is encountered, and a pointer to y is saved somewhere. Then, one(y) is encountered, and a function call is generated. The first statement in one() is "x:=x+1;". Since x is really a pointer to y, y's value is changed to 5. Then the return value of one() is set to x (5), and the function returns. Now the expression can be evaluated. The program looks in y, sees 5, multiplies it by the return value of one(), which is 5, and comes up with 25, which is what you see printed. > end. > > Edwin J. Kay > CSEE > Lehigh University - Mike -- |XXX| __/\__ |XXX|--------------------------+-----------------********========= |XXX| \ / |XXX| Michael D. Ketchen | This space ********========= |XXX| /____\ |XXX| mketch@pawl.rpi.edu | for rent... ================= |XXX| ][ |XXX| mketch@rpitsmts.bitnet +-----------------=================