function f nVars implementation: possible to just add nVars to SP rather than push 0 nVars times?

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

function f nVars implementation: possible to just add nVars to SP rather than push 0 nVars times?

kb-math
The implementation of "function f nVars" as described in the lectures/slides seems to claim that we must push 0 nVars times. I see that the main effect that this has is *SP += nVars, i.e., move SP now points nVars down. Hence would it not be simpler and even more efficient ( O(1) complexity rather than O(nVars)) to just adjust the SP? Sure, the local variables may not be initialized as 0, but surely if a function relies on certain initial values of local variables then it should just set them (to 0 or whatever) itself?
Reply | Threaded
Open this post in threaded view
|

Re: function f nVars implementation: possible to just add nVars to SP rather than push 0 nVars times?

WBahn
Administrator
As long as you adhere to the defined behavior of the language, how you implement those behaviors is completely up to you. Many languages, especially more modern languages, specify that all variables will automatically be initialized to zero. This is because many programmers are sloppy and assume that they are, no matter how many times they are told that they are not. I don't believe Jack requires any such behavior, so doing what you are asking is perfectly acceptable. It is also the primary reason that older languages generally don't initialize local variables.