Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!csd4.csd.uwm.edu!uakari.primate.wisc.edu!ctrsol!emory!stiatl!tom From: tom@stiatl.UUCP (Tom Wiencko) Newsgroups: comp.lang.pascal Subject: Re: Funny evaluation of functions Keywords: functions, precedence Message-ID: <6599@stiatl.UUCP> Date: 23 Aug 89 19:46:23 GMT References: <614@lehi3b15.csee.Lehigh.EDU> Reply-To: tom@stiatl.UUCP (Tom Wiencko) Organization: Wiencko & Associates, Inc. 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? >> >> 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. Sure. You are changing the value of 'y' to 5 since the parameter to function 'one' is a var parameter. If this side effect is not what you wanted, the function should be written so: Function one(x:integer):integer; begin one := x + 1; end; This is, of course, the difference between passing values by reference (var) and passing them by value (as above). You generally do not want to pass by reference if you plan on monkeying with the passed variables unless you want the side effects. Actually, I recommend to beginning programmers that they not use passed parameters as working variables at all unless they are sure they know what they are doing, to prevent just this sort of thing. Side effects of passing variables by reference are horrible to find. In this case, because the compiler did not bother to get the 'y' value before it executed the 'one' function you got nailed. Most compilers will do this - evaluate functions first, then fetch variables. Tom -- Tom Wiencko (w) (404) 977-4515 gatech!stiatl!tom Wiencko & Associates, Inc.