Solidity documentation states that

the default (location -ronme) for local variables is storage

I understand that this makes sense so that localVar = contractStorageVar will result in localVar pointing, and not copying, contractStorageVar.

I'm trying to figure out how this works. For example, as local variables go out of scope, does their storage clear up?


No, storage variables are not cleared when they go out of scope. In most cases, you shouldn't be declaring local storage variables regardless, and the compiler will give you a warning if you try to.

In most cases, if you want to use types like arrays locally, you should explicitly declare them as memory variables like:

bytes memory myVariable = "abcd";

Note that the storage of your contract is essentially unlimited, but writing to storage is extremely expensive. Clearing storage (i.e. setting a nonzero byte to zero) refunds some of the gas.

If you don't intend to use a variable outside of your current scope, there's generally no reason to write the variable to storage. Note that memory variables are passed by reference as well, not copied.

  • Thank you Tjaden. Is it correct, though, that any local variable, by default, is storage? If so, do you recommend setting all of them to zero before the function ends? – ronme Nov 3 '16 at 2:52
  • 1
    Only arrays(including bytes and string)are stored in storage by default. Anything under 32 bytes is just kept on the stack. If you are setting things to zero when the function ends, you should be explicitly declaring them as memory variables, not using storage. – Tjaden Hess Nov 3 '16 at 3:41
  • "Clearing storage (i.e. setting a nonzero byte to zero) refunds some of the gas." --- important reminding! – Suge Dec 16 '17 at 8:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.